他的定义衍生出了一个函数,它使用了一个我只是模糊地熟悉的编译指示。他的定义是
{-# LANGUAGE DeriveFunctor #-}
data Tree a = Leaf a | Node (Tree a) (Tree a)
deriving (Functor, Show)
我无法在GHCI中使用编译指示和定义。以下是我的三次错误尝试,我将不胜感激任何反馈!
首次尝试:
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’
答案 0 :(得分:6)
在GHCi中,您设置编译语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,所以这里有两个错误; data
子句没有问题,但你不能启用像这样的pragma;和