这个"无实例"错误的解决方案是什么?

Ayr*_*lin 2 haskell

我创建了描述二叉树的新类型

data BinTree a = Null | Num a (BinTree a) (BinTree a)
deriving (Show)
Run Code Online (Sandbox Code Playgroud)

并创建了以下功能:

treehandle :: BinTree a -> Bool
treehandle a = True
Run Code Online (Sandbox Code Playgroud)

检查至少输入值.

当我输入值Null时,程序输出结果成功,但我无法输入二叉树.我这样试试:

treehandle (5 (Null) (Null))
Run Code Online (Sandbox Code Playgroud)

但获得:

<interactive>:66:13:
No instance for (Num (BinTree a1 -> BinTree a2 -> BinTree a0))
  (maybe you haven't applied enough arguments to a function?)
  arising from the literal ‘5’
In the expression: 5
In the first argument of ‘treehandle’, namely ‘(5 (Null) (Null))’
In the expression: treehandle (5 (Null) (Null))
Run Code Online (Sandbox Code Playgroud)

为什么?

Sil*_*olo 12

你忘记了值构造函数的名字

treehandle (Num 5 (Null) (Null))
Run Code Online (Sandbox Code Playgroud)

  • @AyratArifullin试着问一下空树案的同样问题.如果你没有输入构造函数的名字,即`Null`,你认为你会输入什么?(还有其他很好的理由,但是应该让你开始思考正确的方向.) (6认同)
  • 简短而甜蜜的解释如何解决问题.另一半问题是"我得到的错误与我输入的代码有什么关系?".那里的答案是`5(Null)(Null)`是一个试图将函数`5`应用于参数`(Null)`和`(Null)`的表达式 - 但是`5`不是函数. (5认同)

ste*_*eve 7

如果我是你,我会为数据构造函数找到不同的命名.Num也是类型类的名称,在查看错误消息时可能会非常混乱.

deriving Show没有正确缩进,你忘了数据构造函数treehandle (5 (Null) (Null)).这是一个工作版本.

data BinTree a = Leaf | Node a (BinTree a) (BinTree a) deriving Show

treehandle :: BinTree a -> Bool
treehandle _ = True

test = treehandle $ Node 5 Leaf Leaf
Run Code Online (Sandbox Code Playgroud)

treehandle想要一个类型的值,BinTree a你给它的所有是一个Int和两个空BinTree's,它实际上尝试应用Int两个空BinTree's和失败.你必须制作一个可以传递给你Node的单曲BinTree atreehandle