【问题标题】:How to properly define a datatype in ghci with Pragma dependency?如何在 ghci 中正确定义具有 Pragma 依赖关系的数据类型?
【发布时间】:2018-04-17 19:13:15
【问题描述】:

我正在尝试根据 Haskell Map for Treeshammar 的回答在 Tree 类型上定义 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’

【问题讨论】:

标签: haskell ghci


【解决方案1】:

在 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)

尝试失败的解释

  1. 第一个失败是因为你的data 子句跨越了多行,所以你应该放在一行上,或者使用某种分组。不过,您并没有启用 pragma,所以这里有两个错误;
  2. 现在data 子句没有问题,但是您不能启用这样的编译指示;和
  3. 编译指示又是问题所在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 2017-10-10
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多