Print instructions in Prolog

In Prolog predicates, I often write repetitive conditional statements like this, but I would like them to be written more briefly:

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

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

+7
switch-statement prolog
source share
3 answers

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

For example, you can implement a switch design, for example

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

defining

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

If necessary, this can be more efficient due to compilation time conversion supported by many Prolog systems ( inline / 2 in ECLiPSe, or target extension in several other systems).

And through operator declarations, you can customize the syntax for just about anything.

+6
source share

It seems that a few suggestions have been made for this use case, and are also rather brief.

 output(javascript, Type, ["javascript", Type]). output(ruby, Type, ["def", Type]). output(java, Type, [Type]). 
+6
source share

a little 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] ]). 
+1
source share

All Articles