Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional writing in Prolog

Tags:

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?

like image 602
dokichan Avatar asked Jan 29 '26 22:01

dokichan


1 Answers

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).
like image 195
dokichan Avatar answered Feb 01 '26 19:02

dokichan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!