首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >可存储对象的Haskell异构列表

可存储对象的Haskell异构列表
EN

Stack Overflow用户
提问于 2016-07-08 13:52:11
回答 0查看 97关注 0票数 1

我想写一个函数,它可以插入不同类型的可存储对象的列表

代码语言:javascript
复制
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RankNTypes, ExistentialQuantification, ImpredicativeTypes #-}

pokeMany :: Ptr b -> Int -> [forall a. Storable a => a] -> IO ()
pokeMany _ _ [] = return ()
pokeMany ptr offset (x:xs) = do
    pokeByteOff ptr offset x
    pokeMany ptr (offset + sizeOf x) xs

somePoke :: Ptr a -> Int -> Int -> IO ()
somePoke ptr x1 x2 = pokeMany ptr 0 [x1, x2]

但是我得到了编译错误:

代码语言:javascript
复制
No instance for (Storable a1) arising from a use of `sizeOf'
The type variable `a1' is ambiguous
Note: there are several potential instances:
  instance Storable CChar -- Defined in `Foreign.C.Types'
  instance Storable CClock -- Defined in `Foreign.C.Types'
  instance Storable CDouble -- Defined in `Foreign.C.Types'

Couldn't match expected type `a2' with actual type `Int'
  `a2' is a rigid type variable bound by
       a type expected by the context: Storable a2 => a2

还有其他的..。

然后我创建了一些数据类型

代码语言:javascript
复制
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RankNTypes, ExistentialQuantification, ImpredicativeTypes #-}

data AnyStorable = forall a. Storable a => AnyStorable a

pokeMany :: Ptr b -> Int -> [AnyStorable] -> IO ()
pokeMany _ _ [] = return ()
pokeMany ptr offset (AnyStorable x:xs) = do
    pokeByteOff ptr offset x
    pokeMany ptr (offset + sizeOf x) xs

somePoke :: Ptr a -> Int -> Int -> IO ()
somePoke ptr n c = pokeMany ptr 0 [AnyStorable n, AnyStorable c, AnyStorable 'a']

上面的代码没有任何编译错误。

我可以在不创建AnyStorable这样的新数据类型的情况下编写pokeMany函数吗?

EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38259745

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档