gpt4 book ai didi

haskell - 开始 Haskell - 出现 "not in scope: data constructor"错误

转载 作者:行者123 更新时间:2023-12-03 12:12:01 24 4
gpt4 key购买 nike

我正在研究 Haskell O'Reilly 书中的问题。我正在处理的问题是

Using the binary tree type that we defined earlier in this chapter, 
write a function that will determine the height of the tree. The height
is the largest number of hops from the root to an Empty. For example, the
tree Empty has height zero; Node "x" Empty Empty has height one;
Node "x" Empty (Node "y" Empty Empty) has height two; and so on.

我在一个名为 ch3.hs 的文件中编写我的代码。这是我的代码:
36 data Tree a = Node a (Tree a) (Tree a)
37 | Empty
38 deriving (Show)
39
40 --problem 9:Determine the height of a tree
41 height :: Tree -> Int
42 height (Tree node left right) = if (left == Empty && right == Empty) then 0 else max (height left) (height right)

在终端中打开 ghci 并输入 :load ch3.hs。当我这样做时,我收到以下错误:
Prelude> :load ch3.hs
[1 of 1] Compiling Main ( ch3.hs, interpreted )

ch3.hs:42:7: Not in scope: data constructor `Tree'
Failed, modules loaded: none.

我希望 Tree 数据构造函数应该在那里,因为我在 height 方法上方的行中定义了它。但是当我尝试加载文件时,我被告知数据构造函数不在范围内。感谢您对为什么会发生此错误的帮助和解释。谢谢,
凯文

最佳答案

改变

height (Tree node left right) 


height (Node node left right)

这意味着模式匹配适用于 algebraic data type 的构造函数。 (ADT)。 Tree不是构造函数,它是 ADT 的名称。

顺便说一句,你必须注释掉你的函数签名声明来编译代码,因为它包含一个错误。

然后,您可以通过以下方式检查推断的类型

:t 高度

ghcihugs .

关于haskell - 开始 Haskell - 出现 "not in scope: data constructor"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3592212/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com