0

我是使用 Ghci 的 Haskell 新手。

我有一个函数,叫做三,我想写成

let three =  \x->(\y->(x(x(x y)))) 

好的,这可行,但是当我尝试时

three (2+) 4

这没用。相反,我得到了一些“无法构造无限类型”的错误。

请帮我。

4

2 回答 2

6
ghci> let three = \x->(\y->(x(x(x y))))
ghci> three (2+) 4
10
ghci> three return "deconstructivist"

<interactive>:1:6:
    Occurs check: cannot construct the infinite type: t = m t
      Expected type: t
      Inferred type: m t
    In the first argument of 'three', namely 'return'
    In the expression: three return "deconstructivist"
ghci> :t three
three :: (t -> t) -> t -> t
ghci> :t return
return :: (Monad m) => a -> m a
  • 您提供的示例three (2+) 4,有效!更好地检查您提供的示例是否确实重现了您的问题。
  • 至于一个不同的例子,比如上面的例子,return问题是返回的结果与给定的类型不同。如果类型相同,它将是无限的(并且是 kind * -> * -> * -> ...),这是 Haskell 不支持的。
于 2009-10-28T22:16:52.103 回答
0

你给出的例子确实有效。让我们解释一下原因:

three f = f . f . f
-- so...
three :: (a -> a) -> a -> a

该函数需要具有类型a -> a,因为它将接收它自己的参数,这需要一个类型。(2+)有 type Num a => a -> a,所以three (2+) 4可以正常工作。

然而,当你传递一个类似returntype的函数时,它返回一个不同的类型,它与我们提出的要求Monad m => a -> m a不匹配。(a -> a)这是您的功能将失败的地方和时间。

当您使用它时,请尝试创建一个类似doTimeswith type的函数Integer -> (a -> a) -> a -> a,该函数执行给定函数给定的次数 - 这是创建此函数之后的一个很好的下一步。

于 2014-12-03T17:10:48.793 回答