Prolog "switch" statement

227 Views Asked by At

How can I implement a switch statement equivalent to a nested set of if_s?

Ideally something like (don't mind the syntax):

compatible(X, Y) :-
    switch X
    a1 -> dif(Y, b2),
    a2 -> dif(Y, c2), dif(Y, c3),
    _  -> true 

working the same way as this one:

compatible(X, Y) :-
    if_(X = a1, 
        dif(Y, b2),
        if_(X = a2, 
            (dif(Y, c2), dif(Y, c3)),
            true
        )
    ).  
1

There are 1 best solutions below

5
vasily On
:- module(switch_, []).

:- use_module(library(reif)).

:- multifile goal_expansion/2.

user:goal_expansion(switch_(X, ;(->(H, C), T)), if_(X = H, C, switch_(X, T))).
user:goal_expansion(switch_(X, ->(H, C)),       if_(X = H, C, fail)).
user:goal_expansion(switch_(_, true),           true).
user:goal_expansion(switch_(_, false),          false).
:- use_module(switch_).

likes(A, B) :-
   switch_(A, (
      john -> B = mary ;
      mary -> dif(B, john) ;
      true
   )).

Example

?- likes(A, B).
A = john,
B = mary ;
A = mary,
dif(B, john) ;
dif(A, mary),
dif(A, john).

?- likes(mary, B).
dif(B, john).

?- likes(john, B).
B = mary.