# natural number(必要のない数も存在する)ZERO = -> s { -> x { x } }
ONE = -> s { -> x { s[x] } }
TWO = -> s { -> x { s[s[x]] } }
THREE = -> s { -> x { s[s[s[x]]] } }
FOUR = -> s { -> x { s[s[s[s[x]]]] } }
FIVE = -> s { -> x { s[s[s[s[s[x]]]]] } }
TEN = -> s { -> x { s[s[s[s[s[s[s[s[s[s[x]]]]]]]]]] } }
FIFTEEN = -> s { -> x { s[s[s[s[s[s[s[s[s[s[s[s[s[s[s[x]]]]]]]]]]]]]]] } }
# boolTRUE = -> x { -> y { x } }
FALSE = -> x { -> y { y } }
# ifIF = -> b { b }
IS_ZERO = -> n { n[-> x { FALSE }][TRUE] }
IS_ONE = -> n { IS_ZERO[SUB[n][ONE]] }
# pairPAIR = -> x { -> y { -> f { f[x][y] } } }
LEFT = -> p { p[-> x { -> y { x } }] }
RIGHT = -> p { p[-> x { -> y { y } }] }
# operatorSUCC = -> n { -> s { -> x { s[n[s][x]] } } }
SLIDE = -> p { PAIR[RIGHT[p]][SUCC[RIGHT[p]]] } # ペア型を引数に取り、右の値と右の値+1したペア型のデータを返すPRED = -> n { LEFT[n[SLIDE][PAIR[ZERO][ZERO]]] }
ADD = -> m { -> n { n[SUCC][m] } } # n + mSUB = -> m { -> n { n[PRED][m] } } # n - m# z-combinatorZ = -> f { ->x { f[-> y { x[x][y] }] }[-> x { f[-> y { x[x][y] }] }] }
# listEMPTY = PAIR[TRUE][TRUE]
UNSHIFT = -> l { -> x { PAIR[FALSE][PAIR[x][l]] } }
IS_EMPTY = LEFTFIRST = -> l { LEFT[RIGHT[l]] }
REST = -> l { RIGHT[RIGHT[l]] }
# comparableIS_LESS_OR_EQUAL = -> m { -> n { IS_ZERO[SUB[m][n]] } }
RANGE = Z[-> f {
-> m { -> n {
IF[IS_LESS_OR_EQUAL[m][n]][
-> x { UNSHIFT[f[SUCC[m]][n]][m][x] }
][
EMPTY
]
} }
}]
# 畳み込み演算FOLD = Z[-> f {
-> l { -> x { -> g {
IF[IS_EMPTY[l]][x][
-> y {
g[f[REST[l]][x][g]][FIRST[l]][y]
}
]
} } }
}]
# mapMAP = -> k { -> f { FOLD[k][EMPTY][-> l { -> x { UNSHIFT[l][f[x]] } }] } }
defto_nat(nat)
nat[-> n { n + 1 }][0]
enddefto_bool(bool)
IF[bool][true][false]
enddefto_ary(proc)
ary = []
until to_bool(IS_EMPTY[proc])
ary << FIRST[proc]
proc = REST[proc]
end
ary
end# フィボナッチ数列の漸化式FIB = Z[-> f {
-> n {
IF[IS_ZERO[n]][
-> x { ZERO }
][IF[IS_ONE[n]][
-> x { ONE }
][
-> x {
ADD[f[PRED[n]]][f[PRED[PRED[n]]]]
}
]][ZERO]
}
}]
proc = MAP[RANGE[ZERO][TEN]][-> n { FIB[n]} ]
results = to_ary(proc).map { to_nat(_1) }
p results #=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
# natural numberZERO = -> s { -> x { x } }
ONE = -> s { -> x { s[x] } }
TWO = -> s { -> x { s[s[x]] } }
TEN = -> s { -> x { s[s[s[s[s[s[s[s[s[s[x]]]]]]]]]] } }
# operatorSUCC = -> n { -> s { -> x { s[n[s][x]] } } }
# ペア型を引数に取り、右の値と右の値+1したペア型のデータを返すSLIDE = -> p { PAIR[RIGHT[p]][SUCC[RIGHT[p]]] }
PRED = -> n { LEFT[n[SLIDE][PAIR[ZERO][ZERO]]] }
ADD = -> m { -> n { n[SUCC][m] } } # n + mSUB = -> m { -> n { n[PRED][m] } } # n - m
FIB = Z[-> f {
-> n {
IF[IS_ZERO[n]][
-> x { ZERO }
][IF[IS_ONE[n]][
-> x { ONE }
][
-> x {
ADD[f[PRED[n]]][f[PRED[PRED[n]]]]
}
]][ZERO]
}
}]
proc = MAP[RANGE[ZERO][TEN]][-> n { FIB[n]} ]