如何使用 ghci 在 lambda 中写入数字
我是 Haskell 新手,使用 Ghci。
我有一个名为三的函数,我想将其写为
let three = \x->(\y->(x(x(x y))))
“OK”,这可以工作,但是当我尝试时
three (2+) 4
它不起作用。相反,我收到一些“无法构造无限类型”错误。
请帮我。
I am new to Haskell, using Ghci.
I have a function, called three, that I want to write as
let three = \x->(\y->(x(x(x y))))
OK, this works, but when I try
three (2+) 4
It does not work. Instead, I get some "cannot construct infinite type" error.
Please help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
三 (2+) 4
示例有效!最好检查您提供的示例是否确实重现了您的问题。return
示例,问题是 return 结果的类型与给定的类型不同。如果类型相同,它将是无限的(并且类型为* -> * -> * -> ...
),Haskell 不支持这种情况。three (2+) 4
, works! Better check that the examples you provide actually reproduce your problem.return
, the thing is that return results in a different type than the one given. If the type was the same, it would be infinite (and of kind* -> * -> * -> ...
), which Haskell does not support.你给出的例子确实有效。让我们解释一下原因:
该函数需要具有类型
a -> a
因为它将接收它自己的参数,这需要一个类型。(2+)
的类型为Num a =>;一个-> a
,所以三 (2+) 4
就可以正常工作。但是,当您传递
return
等类型为Monad m => 的函数时,一个-> m a
,它返回不同的类型,它与我们设定的(a -> a)
要求不匹配。这就是你的函数将在何时何地失败的地方。当你这样做时,尝试创建一个类似
doTimes
的函数,其类型为Integer ->; (a->a)->一个-> a
执行给定的函数给定的次数 - 这是创建此函数后的一个很好的下一步。The example you give does work. Let's explain why:
The function needs to have type
a -> a
because it will receive it's own argument, which requires a type.(2+)
has typeNum a => a -> a
, sothree (2+) 4
will work just fine.However, when you pass a function like
return
of typeMonad m => a -> m a
, which returns a different type, it will not match the(a -> a)
requirement we set out. This is where and when your function will fail.While you're at it, try making a function like
doTimes
with typeInteger -> (a -> a) -> a -> a
which does the given function the given number of times - it's a good next step after making this function.