Skip to content

Instantly share code, notes, and snippets.

@ecnelises
Created November 24, 2017 16:43
Show Gist options
  • Save ecnelises/3c77cce0f520d9a479aace6e8a112290 to your computer and use it in GitHub Desktop.
Save ecnelises/3c77cce0f520d9a479aace6e8a112290 to your computer and use it in GitHub Desktop.
Ruby 版本的阴阳谜题
# 所谓阴阳谜题,即是写一个递归的程序,无休止地输出 @*@**@***... 这样的字符串
# 当然,这里的要求是不能用到常规的数字加减,而是要通过程序的控制流来反映
# 由于 Scheme 语言中存在 call/cc 这个方法,实现阴阳谜题特别方便
# Ruby 其实也是有 call/cc 的,不过现在属于 deprecated 的状态
# 这里用基本的递归实现
# 由于没有显式的 call/cc,这里得把程序写成 CPS 的形式
callcc_cps = -> (f, cont) {
f.(cont)
}
# 一个函数通常来说是难以递归调用自身的
# 解决的办法是把它自己作为参数传给另一个函数
cc_apply = -> (cont) {
cont.(cont)
}
-> {
callcc_cps.(
cc_apply,
-> (v1) {
print '@'
callcc_cps.(
cc_apply,
-> (v2) {
print '*'
v1.(v2)
}
)
}
)
}.call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment