如何使用Haskell在教堂数字中获取取幂函数?
我正在尝试应用规则,即λxy.yx,但有些东西不能正常工作。
exponentiation :: (Num a) => Func a
exponentiation x y = y x
答案 0 :(得分:5)
教会数字算术往往涉及相当奇怪的类型,因此它在Haskell中不如在无类型语言中那么优雅。原则上,教会数字是一个函数,它接受任何endomorphism 并给出同一类型的另一个内同态,即
five :: (a -> a) -> a -> a
适用于任何类型a
,即它实际上意味着
{-# LANGUAGE ExplicitForall, UnicodeSyntax #-}
five :: ∀ a . (a -> a) -> a -> a
当您使用这些数字进行有趣的算术时,技巧可能实际上是处理不同类型的内同态,包括本身是高阶函数的内同态。跟踪这一切非常棘手。
因此,在Haskell中使用Church算法玩弄最不痛苦的方法是将所有多态性包装成单一类型的自然数(其实现恰好是Church编码):
{-# LANGUAGE RankNTypes, UnicodeSyntax #-}
newtype Nat = Nat {getChurchNum :: ∀ a . (a -> a) -> a -> a}
然后你可以给所有基本操作清除类型签名,只需要总是需要在Nat
包装器中放置与数字对应的术语来隐藏多态:
zero :: Nat
zero = Nat (\f x -> x)
suc :: Nat -> Nat
suc = \(Nat n) -> Nat (\f x -> n f (f x))
...或者,因为我更喜欢写它,
instance Enum Nat where
succ (Nat n) = Nat (\f -> n f . f)
instance Num Nat where
fromInteger 0 = Nat (const id)
fromInteger n = succ . fromInteger $ n-1
Nat a + Nat b = Nat (\f -> a f . b f)
Nat a * Nat b = Nat (a . b)
instance Show Nat where
show (Nat n) = show (n (+1) 0 :: Int)
快速测试:
GHCi> [0, 1, 2, 4, 8, 3+4, 3*4 :: Nat]
[0,1,2,4,8,7,12]
现在使用这些类型,您还可以直接实现取幂:
pow :: Nat -> Nat -> Nat
pow (Nat n) (Nat m) = Nat (m n)
它按预期工作:
GHCi> [pow a b :: Nat | a<-[0,1,2,3], b<-[0,1,2,3]]
[1,0,0,0,1,1,1,1,1,2,4,8,1,3,9,27]
答案 1 :(得分:2)
这是使用WinHugs的另一个示例:
type Church a = (a -> a) -> a -> a
zero :: Church a
zero = \s z -> z
one :: Church a
one = \s z -> s z
two :: Church a
two = \s z -> s (s z)
three :: Church a
three = \s z -> s (s (s z))
four :: Church a
four = \s z -> s (s (s (s z)))
succ :: Church a -> Church a
succ n f = f . n f
add :: Church a -> Church a -> Church a
add x y = \s z -> x s (y s z)
mult :: Church a -> Church a -> Church a
mult x y = x.y
exp :: Church a -> (Church a -> Church a) -> Church a
exp x y = y x
测试操作add
,mult
和exp
(使用s=(+1)
和z=0
):
Main> add two three (+1) 0
5
Main> mult four three (+1) 0
12
Main> exp two three (+1) 0
8
测试操作add
,mult
和exp
(使用s=('|':)
和z=""
):
Main> add two three ('|':) ""
"|||||" --5 sticks
Main> mult four three ('|':) ""
"||||||||||||" --12 sticks
Main> exp two three ('|':) ""
"||||||||" --8 sticks
或exp four two
(4 ^ 2 = 16),其写为:
Main> two four (+1) 0
16
一切正常!