仅在haskell中的函数内键入匹配项

时间:2016-04-15 10:27:05

标签: haskell

我是haskell的初学者,并试图实现自然数字的Church编码,如this guide中所述。

{-# LANGUAGE RankNTypes #-}

newtype Chur = Chr (forall a. (a -> a) -> (a -> a))

zero :: Chur
zero = Chr (\x y -> y)

-- church to int
c2i :: Chur -> Integer
c2i (Chr cn) = cn (+ 1) 0

-- this works
i1 = c2i zero
-- this doesn't
i2 = zero (+ 1) 0

对于i2我的类型不匹配:

Couldn't match expected type ‘(Integer -> Integer) -> Integer -> t’
            with actual type ‘Chur’
Relevant bindings include i2 :: t (bound at test.hs:14:1)
The function ‘zero’ is applied to two arguments,
but its type ‘Chur’ has none
In the expression: zero (+ 1) 0
In an equation for ‘i2’: i2 = zero (+ 1) 0

Chur如何在函数中包含参数,但如果没有函数则不能参数?

1 个答案:

答案 0 :(得分:8)

包含在函数中时,

Chur不会接受任何参数 - Chur中包含的函数会执行:

c2i (Chr cn) = cn (+ 1) 0

此处,cn是包含在Chur内的函数。

您可以使用替换方法查看正在发生的事情:

    c2i zero
==> c2i (Chr (\x y -> y))
==> (\x y -> y) (+ 1) 0
==> 0

但是

    zero (+ 1) 0
==> (Chr (\x y -> y)) (+ 1) 0

由于(Chr (\x y -> y))不是函数,因此不起作用。

如果你写了

c2i :: Chur -> Integer
c2i cn = cn (+ 1) 0
你会看到类似的错误。