简体   繁体   English

Haskell中的递归仿函数实例

[英]Recursive functor instance in haskell

i come across a problem with haskell about recursive Functor instance. 我遇到了Haskell关于递归Functor实例的问题。

data List x = Hol | Hoofd x (List x)
            deriving (Show,Eq,Ord)
instance Functor List where 
        fmap f (Hoofd x (Hoofd x)) = Hoofd (f x) Hoofd(f x)
        fmap f Hol               = Hol     
        fmap f Hoofd x (Hol)     = Hoofd (f x)  

I made a datatype List in which i need to inplement the Functor Fmap instance, i tried to use in the datatype deriving (Functor) but i gives me back an error with: can't derive Functor must use DeriveFunctor which i also did not understand... 我创建了一个数据类型列表,我需要在其中填充Functor Fmap实例,我试图在数据类型派生(Functor)中使用它,但是我给了我一个错误:无法派发Functor必须使用DeriveFunctor,而我也不明白...

please help 请帮忙

There are two ways you can make a class-instance for some type: either 有两种方法可以使一个类的实例为某种类型: 要么

  • Use a deriving clause. 使用deriving子句。 This only works for simple classes where there's one obvious way to define the instance's methods. 这仅适用于简单的类,其中有一种明显的方法可以定义实例的方法。 In Haskell98, these classes were only Eq , Ord , Enum , Bounded , Show , and Read . 在Haskell98中,这些类仅为EqOrdEnumBoundedShowRead By now, the language has evolved a lot and GHC can now derive many more classes, but it always requires switching on a language extension . 到目前为止,语言已经发展了很多,GHC现在可以派生更多的类,但是它始终需要打开语言扩展 In particular, to derive Functor , you need to put 特别是要导出Functor ,您需要输入

     {-# LANGUAGE DerivingFunctor #-} 

    at the top of your source file, or alternatively call the compiler/intepreter with 在源文件的顶部,或者使用以下命令调用编译器/解释器

     $ ghc -XDeriveFunctor 

    (I wouldn't recommend the latter; your file wouln't be “self-sufficient” if you do that.) (我不建议后者;如果这样做,您的文件将不会“自给自足”。)

    With that extension enabled, you can simply write 启用该扩展名后,您只需编写

     data List x = Hol | Hoofd x (List x) deriving (Show, Eq, Ord, Functor) 
  • Write the instance yourself. 自己编写实例。 That's what you've done in your code snippet, which has nothing to do with deriving . 这就是您在代码段中所做的,与代码deriving无关。 Your implementation is faulty, which is something you might well ask a question about, but then you should include the information what's currently going wrong. 您的实现是错误的,您可能会问一个问题,但是您应该包括当前出现问题的信息。

EDIT 编辑

found the problem my datatype is recursive but mine Functor instance was not. 发现我的数据类型是递归的问题,但我的Functor实例却不是。

data List x = Hol | Hoofd x (List x)
            deriving (Show,Eq,Ord)


instance Functor List where
            fmap f Hol = Hol
            fmap f (Hoofd x rest) = Hoofd (f x) (fmap f rest)

Now it works, if there is another element which needs to be processed it will be send back to the instance until there is noting to process 现在可以正常工作了,如果还有另一个需要处理的元素,它将被发送回实例,直到没有必要处理为止

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM