SKI 变换,如何用函数式语言编程
我面临以下 Prolog 代码。表达式 [X]>>Y 代表 对于 lambda 表达式 lambda XY 代码消除了 lambda 并给出 S、K 和 I 的组合表达式:
convert([X]>>Y,'I') :- X==Y, !.
convert([X]>>Y,apply('K',Y)) :- var(Y), !.
convert([X]>>([Y]>>Z),R) :-
convert([Y]>>Z,H), convert([X]>>H,R).
convert([X]>>apply(Y,Z),apply(apply('S',S),T)) :-
convert([X]>>Y,S), convert([X]>>Z,T).
convert([_]>>Y,apply('K',Y)).
以下是其工作原理的示例:
?- convert([X]>>([Y]>>apply(Y,X)),R).
R = apply(apply('S', apply(apply('S', apply('K', 'S')),
apply('K', 'I'))), apply(apply('S', apply('K', 'K')), 'I'))
假设我想在 Haskell、ML 或中编写相同的转换 之类的。我该怎么做?我可以使用可用的 lambda 表达式吗 直接用函数式编程语言?或者我必须 回归到一些元编程工具?
最好的问候
P.S.:上面的代码不是导致非常短的 SKI 转换 滑雪表达。可以使用更好的代码来检查是否发生 lambda 表达式主体中的绑定变量。
I am facing the following Prolog code. The expression [X]>>Y stands
for the lambda expression lambda X.Y. The code eliminates the lambda
and gives a combinatory expression over S, K and I:
convert([X]>>Y,'I') :- X==Y, !.
convert([X]>>Y,apply('K',Y)) :- var(Y), !.
convert([X]>>([Y]>>Z),R) :-
convert([Y]>>Z,H), convert([X]>>H,R).
convert([X]>>apply(Y,Z),apply(apply('S',S),T)) :-
convert([X]>>Y,S), convert([X]>>Z,T).
convert([_]>>Y,apply('K',Y)).
Here is an example how it works:
?- convert([X]>>([Y]>>apply(Y,X)),R).
R = apply(apply('S', apply(apply('S', apply('K', 'S')),
apply('K', 'I'))), apply(apply('S', apply('K', 'K')), 'I'))
Suppose I would like to code the same conversion in Haskell, ML, or
the like. How can I do this? Can I use the lambda expressions available
in the functional programming language directly? Or do I have to
regress to some meta programming facilities?
Best Regards
P.S.: The code above is not the SKI conversion that leads to very short
SKI expressions. Better code is possible that checks for occurence of
the bound variable in the lambda expression body.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 prolog 代码几乎可以逐字翻译为 ML 或 Haskell 的模式匹配。当然,您需要为 lambda 表达式定义自己的 ADT。对于该组的最佳组合器和转换,我建议参考 http://www.amazon.com/Functional-Programming-International-Computer-Science/dp/0201192497
Your prolog code can be translated almost verbatim into a pattern matching of ML or Haskell. Of course you'd need to define your own ADT for lambda expressions. And for the most optimal set of combinators and conversion for that set I'd recommend to refer to http://www.amazon.com/Functional-Programming-International-Computer-Science/dp/0201192497
可以直接使用lamdba表达式。在 Haskell 中:(
请注意,我不知道 SKI 的情况,这段代码是将 Wikipedia 上的定义直接转换为 Haskell;它可以工作,但请检查它在概念上是否正确)
You can directly use lamdba expressions. In Haskell:
(note that I didn't know of SKI up to know, this snippet is a direct conversion of the definitions on Wikipedia into Haskell; it works, but do check if it's conceptually right)