1

How can I implement switch case using Prolog Programming Language? I'm very new to the language that is why I have not tried by myself! Let's say we want to change this Java Switch Case into Prolog:

    int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}
repeat
  • 18,496
  • 4
  • 54
  • 166
ShkarM
  • 43
  • 1
  • 7
  • Can you specify what type of "switch case" you're after? In what sense is it dynamic? Generally I would say you cannot do that in prolog, but you can probably model the program logic in another way such that it works. – Limmen May 26 '16 at 14:40
  • The dynamic switch case, strictly speaking, implements a separate function for each different switch action you wish to take. What makes it compact is that it uses the function indexing feature of dynamic link libraries and the case is executed by converting the case value directly to a function index in the DLL. Prolog have a feature for building predicates indexable in a DLL. But the question makes me think you're trying to apply imperative language logic to a relational language. – lurker May 26 '16 at 19:00
  • Possible duplicate of [Switch statements in Prolog](https://stackoverflow.com/questions/35764778/switch-statements-in-prolog) – Anderson Green Jun 22 '18 at 22:02

1 Answers1

1

Do not use imperative programming in Prolog. However, the imperative code:

switch(N) {
    case 1: procedure1(); break;
    case 2: procedure2(); break;
    default: procedure(); break;
    }

May be written as:

switch(1) :-
  procedure1.
switch(2) :-
  procedure2.
switch(_) :-
  procedure;
zebollo
  • 21
  • 1