Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Church Numerals

Name: Anonymous 2013-09-22 17:16

What is this wizardry?


function zero(f) {
    return function (x) {
        return x;
    };
}

function succ(n) {
    return function (f) {
        return function (x) {
            return f(n(f)(x));
        };
    };
}

function multiplyBy2(x) {
    return x * 2;
}

console.log(zero(multiplyBy2)(1)); // => 1
console.log(succ(zero)(multiplyBy2)(1)); // => 2
console.log(succ(succ(zero))(multiplyBy2)(1)); // => 4
console.log(succ(succ(succ(zero)))(multiplyBy2)(1)); // => 8

Name: Anonymous 2013-09-22 17:35


zero :: (a -> a) -> a -> a
zero f x = x

s :: ((a -> a) -> a -> a) -> (a -> a) -> a -> a
s n f x = f (n f x)

main :: IO ()
main = do print $ zero (*2) 1
          print $ (s zero) (*2) 1
          print $ (s (s zero)) (*2) 1
          print $ (s (s (s zero))) (*2) 1

Name: Anonymous 2013-09-22 17:41

install gentoo

Name: Anonymous 2013-09-22 18:23

>>3
You're so funny and original. How do you do it?

Name: Anonymous 2013-09-22 18:38

>>4
Read SICP.

Name: Anonymous 2013-09-23 2:42

>>1

This looks like a convoluted solution to an already solved problem. Also, is there any particular reason why you are currying here? Javascript isn't Haskell, and allows you to use functions with multiple arguments. Unless you need to use it with map or something, you shouldn't use currying. It makes your code less readable.

Name: Anonymous 2013-09-23 5:25

*

Name: Anonymous 2013-09-23 13:27

>>6
Did you even read >>1's code? succ(succ(succ(zero))) would be hell to write without the currying.

Name: Anonymous 2013-09-23 16:37

>>8

Yes and maybe you might just realize that succ(succ(succ(succ(...)))) is a bad idea.

pow2 = (x) ->
  switch
    when x < 0 then 1 / pow2(-x)
    when x is 0 then 1
    else 2 * pow2(x - 1)

console.log pow2(i) for i in [0..3]


CoffeeScript.

Don't change these.
Name: Email:
Entire Thread Thread List