我正在经历Haskell O'Reilly书中的问题。我正在处理的问题是开始Haskell - 获取“不在范围内:数据构造函数”错误
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.
我想到的是,树的数据构造应该有,因为我在高处方法行定义它。但是当我尝试加载文件时,我被告知数据构造函数不在范围内。感谢您的帮助,并解释为何发生此错误。谢谢, 凯文
谢谢,工作。我仍然不完全理解正在发生的事情,并且现在在运行时遇到错误,但会继续盯着思考和调试。 – 2010-08-28 20:17:23
另一个例子可能会使它更容易理解。假设我们正在使用整数,而不是树。 Int是整数类型的名称。您不能添加“Int + Int”,因为Int是类型的名称,而不是返回该类型值的构造函数。像0,1,2这些东西是构造函数,如果你想使用整数,那就是你如何让它们进入你的程序。把这个应用到你的案例中,'Tree'是类型的名称,'Node'(或'Empty')是你如何获得*这种类型的值。 – jrockway 2010-08-29 01:44:34
HaskellWiki也有一个有用的部分,它甚至使用Tree作为示例:http://www.haskell.org/haskellwiki/Constructor – jrockway 2010-08-29 01:45:48