prolog

Conditional writing in Prolog


I have Prolog database with airplane schedules. Here is how it looks:

fly(id, from, to, days(1, 0, 1, 0, 1, 0, 1)).

As you can see there are 7 values in days predicate - from Monday to Sunday. What I want to do is to print every day, where value is 1, but print it into just text. I was trying to use if - else statement, but in this case it doesn't work how it is supposed to:

(   
        A = 1 -> write(monday), nl;
        (
            B = 1 -> write(tuesday), nl;
            (
                C = 1 -> write(wednesday), nl;
                (
                    D = 1 -> write(thursday), nl;
                    (
                        E = 1 -> write(friday), nl;
                        (
                            F = 1 -> write(saturday), nl;
                            (
                                G = 1 -> write(sunday), nl
                            )
                        )
                    )
                )
            )
        )
    )

In example case it should print 4 days:

monday
wednesday
friday
sunday

How can I do that?


Solution

  • I have found a way to do that, basically, you need to create 2 lists. First one is for your days, and the second one is for names of days. Then, you need to iterate them, but, because of fact that there are no loop constructions in Prolog, you have to do that using recursive function.

    Here is how I have implemented it:

    iterate_weeks([], _).
    iterate_weeks([H|T], [X|Y]) :- H = 1, write(X), nl, iterate_weeks(T, Y).
    iterate_weeks([H|T], [_|Y]) :- H = 0, iterate_weeks(T, Y).
    
    print_fly_days(From, To):- 
        fly(_, From, To, _, _, days(A,B,C,D,E,F,G)),
        L = [A,B,C,D,E,F,G],
        T = [monday, tuesday, wednesday, thursday, friday, saturday, sunday],
        iterate_weeks(L, T).