4

我找不到将加法定义为重复递增的方法,尽管这在无类型语言中是可能的。这是我的代码:

{-# LANGUAGE RankNTypes #-}
type Church = forall a . (a -> a) -> (a -> a)

zero :: Church
zero = \f -> id

inc :: Church -> Church
inc n = \f -> f . n f

-- This version of addition works
add1 :: Church -> Church -> Church
add1 n m = \f -> n f . m f

-- This version gives me a compilation error
add2 :: Church -> Church -> Church
add2 n m = n inc m

我得到的编译错误add2

Couldn't match type `forall a1. (a1 -> a1) -> a1 -> a1'
                  with `(a -> a) -> a -> a'
    Expected type: ((a -> a) -> a -> a) -> (a -> a) -> a -> a
      Actual type: Church -> (a -> a) -> a -> a
    In the first argument of `n', namely `inc'
    In the expression: n inc m
    In an equation for `add2': add2 n m = n inc m

为什么这是一个错误?不是Church那个的同义词((a->a) -> a -> a)吗?

4

1 回答 1

5

无论我添加了哪些额外的类型注释,我都无法输入您的代码,尽管我可能不够聪明。(我也尝试添加ImpredicativeTypes。)我认为这里的问题是在定义中

type Church = forall a. (a -> a) -> (a -> a)

a只能用 rank-0 类型(即内部没有 foralls)实例化,而它Church本身不是。因此,您不能将这种方式定义的 Church 数字应用于您的inc.

但是,有一个相对简单的解决方法,它有点冗长,但可以使一切正常工作:将Church其转换为新类型而不是类型,以便可以从外部将其视为单态。以下所有工作:

{-# LANGUAGE RankNTypes #-}
newtype Church = Church { runChurch :: forall a . (a -> a) -> (a -> a) }

zero :: Church
zero = Church (\f -> id)

inc :: Church -> Church
inc n = Church (\f -> f . runChurch n f)

add2 :: Church -> Church -> Church
add2 n = runChurch n inc
于 2014-05-17T03:30:43.540 回答