the*_*cks 7 haskell functional-programming currying higher-order-functions
有很多基于 的问题applyTwice
,但没有一个与我的问题有关。我了解applyTwice
函数定义如下:
applyTwice :: (a -> a) -> a -> a
applyTwice f a = f (f a)
Run Code Online (Sandbox Code Playgroud)
两次应用一个函数。所以如果我有一个增量函数:
increment x = x + 1
Run Code Online (Sandbox Code Playgroud)
并做
applyTwice increment 0
Run Code Online (Sandbox Code Playgroud)
我得到 2. 但我不明白这些结果:
applyTwice applyTwice applyTwice increment 0 -- gives 16
applyTwice applyTwice applyTwice applyTwice increment 0 -- gives 65536
applyTwice applyTwice applyTwice applyTwice applyTwice increment 0 -- stack overflow
Run Code Online (Sandbox Code Playgroud)
我也知道
twice = applyTwice applyTwice increment
applyTwice twice 0 -- gives 8
Run Code Online (Sandbox Code Playgroud)
我根本无法理解这些结果,如果有人能解释一下,我会很高兴的。如果这是基本的东西,我很抱歉,因为我只是在学习 Haskell。
让我们使用非正式的符号
iter n f = f . f . f . .... -- n times
Run Code Online (Sandbox Code Playgroud)
你的applyTwice
就是那么简单iter 2
。
从定义中,我们立即得到:
(iter n . iter m) f
= iter n (iter m f)
= (f.f. ...) . ... . (f.f. ...) -- n times (m times f)
= iter (n*m) f
Run Code Online (Sandbox Code Playgroud)
因此,eta 收缩,
iter n . iter m = iter (n*m) -- [law 1]
Run Code Online (Sandbox Code Playgroud)
我们还有
iter n (iter m)
= -- definition
iter m . iter m . .... . iter m -- n times
= -- law 1
iter (m*m* ... *m) -- n times
= -- power
iter (m^n) -- [law 2]
Run Code Online (Sandbox Code Playgroud)
然后,我们有,写t
的applyTwice
:
t = iter 2
t t
= -- previous equation
iter 2 (iter 2)
= -- law 2
iter (2^2)
t t t
= -- left associativity of application
(t t) t
= -- previous equation
iter (2^2) (iter 2)
= -- law 2
iter (2^(2^2))
t t t t
= -- left associativity of application
(t t t) t
= -- previous equation
iter (2^(2^2)) (iter 2)
= -- law 2
iter (2^(2^(2^2)))
Run Code Online (Sandbox Code Playgroud)
等等。