Subtraction of church numerals in haskell

后端 未结 3 1825
情歌与酒
情歌与酒 2020-12-29 06:06

I\'m attempting to implement church numerals in Haskell, but I\'ve hit a minor problem. Haskell complains of an infinite type with

Occurs check: cannot construct th

3条回答
  •  佛祖请我去吃肉
    2020-12-29 06:30

    I have encountered the same problem. And I solved it without adding type signature.

    Here's the solution, with cons car copied from SICP.

    cons x y = \m -> m x y
    car z = z (\p q -> p)
    cdr z = z (\p q -> q)
    
    next z = cons (cdr z) (succ (cdr z))
    pred n = car $ n next (cons undefined zero)
    
    sub m n = n pred m
    

    You can find full source here.

    I'm really amazed after writing sub m n = n pred m, and load it in ghci without type error!

    Haskell code is so concise! :-)

提交回复
热议问题