-2
我是Haskell和函数式编程的新手。我试图用函数和“加号”函数来实现自然数。我有一个不能改变的给定类型。实现自然数
type Number t = (t -> t) -> t -> t
为此我必须实现“零”的功能,代表数字0,“下一个” 函数返回一个数字和一个“加”功能。
zero :: Number t
zero x = ???
next :: Number t -> Number t
next n = \f z -> ???
plus :: Number t -> Number t -> Number t
plus x y = ???
落实这些后,我应该能够测试:
one :: Number t
one = next zero
tesOne = one (+ 1) 0
two :: Number t
two = plus (next zero) (next zero)
testTwo = (+ 5) 0
在此代码“testOne”应该是1和“testTwo”应该是10 感谢您抽出时间来看看!
我试过了,但我想我还不太了解函数式编程。
zero :: Number t
zero x = (\f ->f) x
next :: Number t -> Number t
next n = \f z -> f z
plus :: Number t -> Number t -> Number t
plus x y = (\f x y -> x + y) x y
阅读https://en.wikipedia.org/wiki/Church_encoding –
你对这个问题有什么想法?你有什么尝试?它出了什么问题? –
尝试使用'zero f x = x'和'next n f x = f(n f x)' – Bergi