haskell - 如何使用 Pragma 依赖项在 ghci 中正确定义数据类型?

标签 haskell ghci

我正在尝试根据 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)

尝试失败的说明:

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

关于haskell - 如何使用 Pragma 依赖项在 ghci 中正确定义数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49885832/

相关文章:

multithreading - 如果与 `putChar` > 1 秒一起使用,Haskell 的 `threadDelay` 不会打印任何内容

design-patterns - Haskell:设计模式:类或传递函数

haskell - 在 Nat 上使用 * 作为原语

haskell - 如何检查局部变量的类型?

macos - 在 ghci 或 ghc 中使用 gcc 而不是 clang

haskell - 模式匹配后多态性丢失

haskell - Aeson:在 Haskell 中使用未知 key 解析 JSON

Haskell - 由于我不明白的原因,非穷举模式

string - 我如何将字符串转换为元组

haskell - 停止 ghci 在提示符中显示模块