我是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
如何在函数中包含参数,但如果没有函数则不能参数?
答案 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
你会看到类似的错误。