Prolog 中的 Switch 语句 [英] Switch statements in Prolog

查看:48
本文介绍了Prolog 中的 Switch 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Prolog 谓词中,我经常写这样的重复条件语句,但我希望它们可以写得更简洁:

In Prolog predicates, I often write repetitive conditional statements like this one, but I wish they could be written more concisely:

output(Lang, Type, Output) :-   
    (Lang = javascript ->
        Output = ["function", Type];
    Lang = ruby ->
        Output = ["def", Type];
    Lang = java ->
        Output = [Type]).

是否可以用更简洁的 switch 语句替换这一系列的条件语句?

Would it be possible to replace this series of conditional statements with a more concise switch-statement?

推荐答案

在 Prolog 中,使用元谓词(将目标或谓词作为参数的谓词)定义您自己的控制结构非常容易.

In Prolog it is quite easy to define your own control structures, using meta-predicates (predicates that take goals or predicates as arguments).

例如,您可以实现像

switch(X, [
    a : writeln(case1),
    b : writeln(case2),
    c : writeln(case3)
])

通过定义

switch(X, [Val:Goal|Cases]) :-
    ( X=Val ->
        call(Goal)
    ;
        switch(X, Cases)
    ).

如有必要,可以通过许多 Prolog 系统支持的编译时转换来提高效率(inline/2 在 ECLiPSe 中,或在其他几个系统中的目标扩展).

If necessary, this can then be made more efficient by compile-time transformation as supported by many Prolog systems (inline/2 in ECLiPSe, or goal expansion in several other systems).

并且通过运算符声明,您可以将语法调整为您喜欢的任何内容.

And via operator declarations you can tweak the syntax to pretty much anything you like.

这篇关于Prolog 中的 Switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆