Switch statements in Prolog

前端 未结 3 1392
死守一世寂寞
死守一世寂寞 2021-01-17 17:51

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

output(Lang, Type, Outp         


        
相关标签:
3条回答
  • 2021-01-17 18:19

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

    For example, you could implement a switch construct like

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

    by defining

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

    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.

    0 讨论(0)
  • 2021-01-17 18:32

    It seems that multiple clauses are made for this use case and also quite concise.

    output(javascript, Type, ["javascript", Type]).
    output(ruby, Type, ["def", Type]).
    output(java, Type, [Type]).
    
    0 讨论(0)
  • 2021-01-17 18:32

    slightly shorter:

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

    idiomatic:

    output(Lang, Type, Output) :-
      memberchk(Lang-Output, [
        javascript - ["function", Type],
        ruby - ["def", Type],
        java - [Type]
      ]).
    
    0 讨论(0)
提交回复
热议问题