我试图在 Haskell Map for Trees的hammar的答案中定义一个Tree类型的fmap 他的定义来自functor,它使用了pragma,我只是模糊地熟悉它.他的定义是 {-# LANGUAGE DeriveFunctor #-}data Tree a = Leaf a | Node (Tree a)
他的定义来自functor,它使用了pragma,我只是模糊地熟悉它.他的定义是
{-# LANGUAGE DeriveFunctor #-} data Tree a = Leaf a | Node (Tree a) (Tree a) deriving (Functor, Show)
我无法在GHCI中使用pragma和定义.以下是我的三次错误尝试,我将不胜感激任何反馈!
第一次尝试:
Prelude> {-# LANGUAGE DeriveFunctor #-} Prelude> data Tree a = Leaf a | Node (Tree a) (Tree a) Prelude> deriving (Functor, Show) <interactive>:30:5: parse error on input ‘deriving’
第二次尝试:
Prelude> {-# LANGUAGE DeriveFunctor #-} Prelude> data Tree a = Leaf a | Node (Tree a) (Tree a) deriving (Functor, Show) <interactive>:32:57: Can't make a derived instance of ‘Functor Tree’: You need DeriveFunctor to derive an instance for this class In the data declaration for ‘Tree’
第三次尝试:
Prelude> :{ Prelude| {-# LANGUAGE DeriveFunctor #-} Prelude| data Tree a = Leaf a | Node (Tree a) (Tree a) Prelude| deriving (Functor, Show) Prelude| :} <interactive>:35:1: parse error on input ‘data’在GHCi中,您设置了pragma with
:set
:
Prelude> :set -XDeriveFunctor
由于data子句跨越多行,因此可以在:{和:}之间声明:
Prelude> :{ Prelude| data Tree a = Leaf a | Node (Tree a) (Tree a) Prelude| deriving (Functor, Show) Prelude| :}
现在它应该工作(在本地测试).我们可以例如执行fmap:
Prelude> fmap (+1) (Node (Leaf 12) (Leaf 25)) Node (Leaf 13) (Leaf 26)
尝试失败的说明:
>第一个失败是因为您的数据子句跨越多行,因此您应该放入一行,或使用某种分组.不过,你没有启用编译指示,所以这里有两个错误;>现在data子句没有问题,但你不能启用像这样的pragma;和>再次,pragma是问题所在.