Haskell:可能的解决方法:将 (Eq a) 添加到 [英] Haskell: Possible fix: add (Eq a) to the context of

查看:20
本文介绍了Haskell:可能的解决方法:将 (Eq a) 添加到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Haskell 的新手,我很难理解我的代码有什么问题.

I'm kind of new to Haskell and I'm having a hard time understanding what is wrong with my code here.

这是我应该做的:
考虑以下二叉树的定义

data BinaryTree a = Empty | Node a (BinaryTree a) (BinaryTree a)  

考虑函数reflect,通过一直向下交换左右来形成二叉树的镜像

reflect :: BinaryTree a -> BinaryTree a  
reflect Empty = Empty  
reflect (Node x l r) = Node x (reflect r) (reflect l)  

编写一个函数 areMirrorImages 判断两棵二叉树 t 和 u 是否满足t = 反映你.该函数不应构建新树,因此不应调用反射或节点;尽管它可能会在模式中使用 Node.

这是我写的:

areMirrorImages :: BinaryTree a -> BinaryTree a -> Bool  
areMirrorImages Empty Empty = True  
areMirrorImages (Node _ _ _) Empty = False  
areMirrorImages Empty (Node _ _ _) = False  
areMirrorImages (Node x l r) (Node y ll rr)  
    | x==y = ((areMirrorImages l rr) && (areMirrorImages r ll))  
    | otherwise = False  

当我尝试运行它时,在第 49 行出现以下错误:
无法从使用=="的上下文 () 推导出 (Eq a)
可能的解决方法:将 (Eq a) 添加到areMirrorImages"的类型签名的上下文中
表达式中:x==y

When I try running it I get the following error on line 49:
Could not deduce (Eq a) from the context () arising from a use of '=='
Possible fix: add (Eq a) to the context of the type signature for 'areMirrorImages'
In the expression: x==y

我很困惑为什么我会收到这个错误,我尝试在网上寻找解决方案,但到目前为止我什么也没找到.谢谢.

I am confused as to why I'm getting this error and I tried finding solutions online but I have found nothing so far. Thanks.

推荐答案

目前,您的二叉树可以容纳任何类型——甚至是无法使用 == 进行比较的类型.所以如果你在包含这种类型的树上调用 areMirrorImages ......会发生什么?

At the moment, your binary trees can hold any type whatsoever - even types that can't be compared using ==. So if you called areMirrorImages on a tree containing such a type ... what should happen?

你需要做的是在areMirrorImages函数上放置一个约束,这样它就只能接受它可以比较内容的二叉树.

What you need to do is place a constraint on the areMirrorImages function, so that it can only accept binary trees that it can compare the contents of.

类似于以下内容:

areMirrorImages :: Eq a => BinaryTree a -> BinaryTree a -> Bool

这篇关于Haskell:可能的解决方法:将 (Eq a) 添加到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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