Last active
September 3, 2017 13:13
用Ruby的Lambda实现基本数值运算
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ZERO = -> p { -> x { x } } | |
ONE = -> p { -> x { p[x] } } | |
TWO = -> p { -> x { p[p[x]] } } | |
THREE = -> p { -> x { p[p[p[x]]] } } | |
FOUR = -> p { -> x { p[p[p[p[x]]]] } } | |
FIVE = -> p { -> x { p[p[p[p[p[x]]]]] } } | |
def to_integer(n) | |
n[-> x {x + 1}][0] | |
end | |
SUCC = -> n { | |
-> p { | |
-> x { | |
p[n[p][x]] | |
} | |
} | |
} | |
ADD = -> n { | |
-> m { | |
n[SUCC][m] | |
} | |
} | |
MULTI = -> n { | |
-> m { | |
n[ADD[m]][ZERO] | |
} | |
} | |
PAIR = -> first { | |
-> second { | |
-> p { | |
p[first][second] | |
} | |
} | |
} | |
LEFT = -> first { | |
-> second { | |
first | |
} | |
} | |
RIGHT = -> first { | |
-> second { | |
second | |
} | |
} | |
SLIDE = -> p { | |
PAIR[p[RIGHT]][SUCC[p[RIGHT]]] | |
} | |
def to_pair(pair) | |
"(#{to_integer(pair[LEFT])}, #{to_integer(pair[RIGHT])})" | |
end | |
PRED = -> n { | |
n[SLIDE][PAIR[ZERO][ZERO]][LEFT] | |
} | |
SUBT = -> m { | |
-> n { | |
n[PRED][m] | |
} | |
} | |
POWER = -> m { | |
-> n { | |
n[MULTI[m]][ONE] | |
} | |
} | |
if __FILE__ == $0 | |
p to_integer(ADD[FOUR][FIVE]) | |
p to_integer(MULTI[FOUR][FIVE]) | |
p to_integer(MULTI[ONE][FIVE]) | |
p to_integer(PAIR[TWO][FIVE][LEFT]) | |
p to_integer(PAIR[TWO][FIVE][RIGHT]) | |
puts to_pair(PAIR[ONE][TWO]) | |
puts to_pair(SLIDE[PAIR[ONE][TWO]]) | |
puts to_pair(SLIDE[SLIDE[PAIR[ONE][TWO]]]) | |
p to_integer(PRED[FOUR]) | |
p to_integer(PRED[TWO]) | |
p to_integer(PRED[ONE]) | |
p to_integer(SUBT[FIVE][ONE]) | |
p to_integer(SUBT[FIVE][TWO]) | |
p to_integer(SUBT[THREE][TWO]) | |
p to_integer(POWER[FIVE][FIVE]) | |
p to_integer(POWER[FOUR][FOUR]) | |
p to_integer(POWER[FOUR][ONE]) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment