[英]Haskell - functor instance with recursive data constructor
I am having trouble implementing a recursive functor instance.我在实现递归仿函数实例时遇到了麻烦。 I have tried as follow, but I receive an error that cannot construct the infinite type: b ~ List b我已经尝试如下,但我收到一个无法构造无限类型的错误:b ~ List b
data List a = Hol x a| Hoofd x [List a]
deriving (Show,Eq,Ord)
instance Functor List where
fmap f Hol x a = Hol x (f a)
fmap f (Hoofd x rest) = Hoofd x (fmap f rest)
Can anyone please suggest me how to fix this and what's my problem?谁能建议我如何解决这个问题,我的问题是什么? Thanks谢谢
The fmap
will work on the list, so perform a mapping. fmap
将在列表上工作,因此请执行映射。 This means that you use f:: a -> b
to convert a List a -> List b
, which will not work: you need another functor mapping, so:这意味着您使用f:: a -> b
来转换List a -> List b
,这将不起作用:您需要另一个仿函数映射,因此:
instance Functor List where
fmap f (Hol x a) = Hol x (f a)
fmap f (Hoofd x rest) = Hoofd x (fmap (fmap f) rest)
or we can work with a helper function:或者我们可以使用助手 function:
instance Functor List where
fmap f = go
where go (Hol x a) = Hol x (f a)
go (Hoofd x rest) = Hoofd x (fmap go rest)
Or we can work with the Compose
type to perform a mapping that is two (or more) layers deep:或者我们可以使用Compose
类型来执行两(或更多)层深度的映射:
import Data.Functor.Compose(Compose(getCompose))
instance Functor List where
fmap f (Hol x a) = Hol x (f a)
fmap f (Hoofd x xs) = Hoofd x (getCompose (fmap f (Compose xs)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.