开始Haskell - 获取“不在范围内:数据构造函数”错误 [英] Beginning Haskell - getting "not in scope: data constructor" error

查看:171
本文介绍了开始Haskell - 获取“不在范围内:数据构造函数”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览Haskell O'Reilly书中的问题。我正在处理的问题是:

 使用我们在本章前面定义的二叉树类型,
写一个函数将决定树的高度。高度
是从根到空的最大跳数。例如,
树Empty有高度零;节点x空的空有一个高度;
节点x空(节点y空的空)具有高度二;等等。

我在一个名为ch3.h的文件中编写我的代码。这里是我的代码:

  36数据树a =节点a(树a)(树a)
37 |空
38导出(显示)
39
40 - 问题9:确定树的高度
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的1]编译Main(ch3.hs,解释)

ch3.hs:42:7:不在范围内:数据构造函数`Tree'
失败,模块加载:无。

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

解决方案

更改

  height(Tree node left right)

to

  height(Node node left right)

这意味着模式匹配对代数数据类型(ADT)的构造函数有效, 。 不是一个构造函数,它是ADT的名称。



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



然后,您可以通过

<$检查推断的类型p $ p>
:t身高

ghci 拥抱


I'm going through the problems in the Haskell O'Reilly book. The problem I am working on is

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.

I'm writing my code in a file called ch3.hs. Here's my code:

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) 

opening ghci in the terminal and typing :load ch3.hs. When I do that I get the following error:

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.

I expect that the Tree data constructor should be there, because I defined it in the lines above the height method. But when I try to load the file, I'm told that the data constructor is not in scope. I appreciate your help and explanation of why this error occurs. Thanks, Kevin

解决方案

Change

height (Tree node left right) 

to

height (Node node left right)

That means the pattern matching works on the constructors of the algebraic data type (ADT). Tree is not a constructor, it is the name of the ADT.

Btw, you have to comment out your function signature declaration to compile the code because it contains an error.

You can then check the inferred type via

:t height

in ghci or hugs.

这篇关于开始Haskell - 获取“不在范围内:数据构造函数”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆