【发布时间】:2011-04-05 06:24:49
【问题描述】:
我正在研究 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 方法上方的行中定义了它。但是当我尝试加载文件时,我被告知数据构造函数不在范围内。感谢您对为什么会发生此错误的帮助和解释。谢谢, 凯文
【问题讨论】: