Skip to content

Instantly share code, notes, and snippets.

@lanzhiheng
Last active September 3, 2017 13:13
Show Gist options
  • Save lanzhiheng/2a87dedb829fdf9ee13963ee60c94d11 to your computer and use it in GitHub Desktop.
Save lanzhiheng/2a87dedb829fdf9ee13963ee60c94d11 to your computer and use it in GitHub Desktop.
用Ruby的Lambda实现基本数值运算
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