原因exp
不能按照您的方式编写,因为它涉及将 aNumeral
作为参数传递给 a Numeral
。这需要有一个Numeral (a -> a)
,但你只有一个Numeral a
。你可以把它写成
exp :: Numeral a -> Numeral (a -> a) -> Numeral a
exp n m = m n
除了不应使用toNumeral
类似的模式这一事实之外,我看不出有什么问题。x + 1
toNumeral :: Integer -> Numeral a -- No need to restrict it to Integer
toNumeral 0 = \f v -> v
toNumeral x
| x > 0 = churchSucc $ toNumeral $ x - 1
| otherwise = error "negative argument"
此外,您sum
的错误,因为m . churchSucc n
is m * (n + 1)
,所以它应该是:
sum :: Numeral a -> Numeral a -> Numeral a
sum m n f x = m f $ n f x -- Repeat f, n times on x, and then m more times.
但是,教堂数字是适用于所有类型的功能。也就是说,Numeral String
不应该与 不同Numeral Integer
,因为 aNumeral
不应该关心它正在处理什么类型。这是一个普遍的量化:Numeral
是一个函数,对于所有类型a
, (a -> a) -> (a -> a)
,它被写成 , with RankNTypes
, as type Numeral = forall a. (a -> a) -> (a -> a)
。
这是有道理的:一个教堂数字是由它的函数参数重复多少次来定义的。\f v -> v
调用f
0 次,所以它是 0,\f v -> f v
是 1,等等。强制 aNumeral
为所有人工作a
确保它只能这样做。但是,允许 aNumeral
关心什么类型f
并v
具有删除限制,并允许您编写(\f v -> "nope") :: Numeral String
,即使这显然不是 a Numeral
。
我会把它写成
{-# LANGUAGE RankNTypes #-}
type Numeral = forall a. (a -> a) -> (a -> a)
_0 :: Numeral
_0 _ x = x
-- The numerals can be defined inductively, with base case 0 and inductive step churchSucc
-- Therefore, it helps to have a _0 constant lying around
churchSucc :: Numeral -> Numeral
churchSucc n f x = f (n f x) -- Cleaner without lambdas everywhere
sum :: Numeral -> Numeral -> Numeral
sum m n f x = m f $ n f x
mult :: Numeral -> Numeral -> Numeral
mult n m = n . m
exp :: Numeral -> Numeral -> Numeral
exp n m = m n
numerify :: Numeral -> Integer
numerify n = n (1 +) 0
toNumeral :: Integer -> Numeral
toNumeral 0 = _0
toNumeral x
| x > 0 = churchSucc $ toNumeral $ x - 1
| otherwise = error "negative argument"
相反,它看起来更干净,并且比原来的更不容易遇到障碍。
演示:
main = do out "5:" _5
out "2:" _2
out "0:" _0
out "5^0:" $ exp _5 _0
out "5 + 2:" $ sum _5 _2
out "5 * 2:" $ mult _5 _2
out "5^2:" $ exp _5 _2
out "2^5:" $ exp _2 _5
out "(0^2)^5:" $ exp (exp _0 _2) _5
where _2 = toNumeral 2
_5 = toNumeral 5
out :: String -> Numeral -> IO () -- Needed to coax the inferencer
out str n = putStrLn $ str ++ "\t" ++ (show $ numerify n)