我正在尝试根据 hammar 在 Haskell Map for Trees 中的回答来定义树类型上的 fmap
他的定义派生仿函数,它使用了一个编译指示,我对此只是模糊地熟悉。他的定义是
{-# 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’
最佳答案
在 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
子句跨越多行,因此您应该放在一行上,或者使用某种分组。然而,您没有启用该编译指示,因此这里有两个错误; - 现在
data
子句没有问题,但是你不能启用这样的编译指示;和 - pragma 又是问题所在。
关于haskell - 如何使用 Pragma 依赖项在 ghci 中正确定义数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49885832/