问题描述
我正在尝试使用Haskell的递归类型创建一个向后列表
I am trying to create a backward list using Haskell's recursive types
data RevList a = Snoc a (RevList a) | Lin
deriving Show
mkrevlst [] = Lin
mkrevlst (x:xs) = mkrevlst xs Snoc x
当我执行>mkrevlst [1,2,3]
,我期望的输出是:((Lin Snoc 3)Snoc 2)Snoc 1
When I do > mkrevlst [1,2,3]
,the output I am expecting is : ((Lin Snoc 3) Snoc 2) Snoc 1
运行此命令时出现错误.我是Haskell&的新手.我无法找出错误所在.我要去哪里错了?
When I run this I get an error. I am new to Haskell & I am not able to make out where is mistake is.Where am I going wrong?
谢谢.
推荐答案
我不确定这行应该是什么,但它本身没有任何意义:
I'm not sure what this line was supposed to be, but it doesn't make sense as is:
mkrevlst (x:xs) = mkrevlst xs Snoc x
表达式 mkrevlist xs
大概具有 RevList a
类型,因为上述基本情况返回了 Lin
.将其应用于另外两个参数确实会导致类型错误.
The expression mkrevlist xs
presumably has type RevList a
, since the base case above returns Lin
. Applying this to two more arguments will indeed result in a type error.
看起来 就像您期望将 Snoc
用作后缀,对吗?在Haskell中,由字母数字字符组成的标识符为前缀,除非被反引号括起来,例如 mkrevlist xs`Snoc` x
.除非用括号括起来,否则由符号组成的标识符为infix,并且infix数据构造函数必须特别以冒号开头.因此,您还可以像这样定义数据类型:
It looks like you're expecting Snoc
to be used infix, is that correct? In Haskell, identifiers made of alphanumeric characters are prefix, unless surrounded by backticks, e.g. mkrevlist xs `Snoc` x
. Identifiers made of symbols are infix, unless surrounded in parentheses, and infix data constructors specifically must start with a colon. So you could also define your data type like this:
data RevList a = a :| (RevList a) | Lin
deriving Show
此外,请注意,即使您确实使用了 Snoc
中缀,其参数的顺序仍然比您在 mkrevlist
中使用它的方式相反.
Also, note that even if you do use Snoc
infix, the order of its arguments are still backwards from how you're using it in mkrevlist
.
这篇关于在Haskell中使用递归数据类型创建向后列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!