CS 3060: Programming Languages

Prolog

Robert C. Green II, Ph.D.

Day 2

Rain Man

Recursion

                        
father(zeb, john_boy_sr).
father(john_boy_sr, john_boy_jr).

ancestor(X, Y) :-
    father(X, Y).

ancestor(X, Y) :-
    father(X, Z), ancestor(Z, Y).
                        
                    

Caution: May break the stack!

Lists & Tuples

                        
[1, 2, 3]

(1, 2, 3)
                        
                    

Lists & Tuples

                        
(1, 2, 3) = (1, 2, 3).

(1, 2, 3) = (1, 2, 3, 4).

(1, 2, 3) = (3, 2, 1).
                        
                    

List Deconstruction

                        
[a, b, c] = [Head|Tail].

[a, b, c] = [a|[Head|Tail]].

 [a, b, c, d, e] = [_, _|[Head|_]]
                        
                    

Can Erlang do this?

Lists

                        
count(0, []).
count(Count, [Head|Tail]) :- count(TailCount, Tail), 
                             Count is TailCount + 1.

count(What, [1]).
                        
                    

Explain what happens here...

Lists

                        
sum(0, []).
sum(Total, [Head|Tail]) :- sum(Sum, Tail), Total is Head + Sum.

sum(What, [1, 2, 3]).
                        
                    

Explain what happens here...

Lists

                        
average(Average, List) :- sum(Sum, List), count(Count, List), 
                          Average is Sum/Count.

Average(What, [1, 2, 3]).
                        
                    

Explain what happens here...

Lists

                        
append([oil], [water], [oil, water]).

append([oil], [water], [oil, slick]).

append([tiny], [bubbles], What).

append([dessert_topping], Who, [dessert_topping, floor_wax]).

append(One, Two, [apples, oranges, bananas]).
                        
                    

Lists

                        
concatenate([], List, List).
concatenate([Head|Tail1], List, [Head|Tail2]) :-
    concatenate(Tail1, List, Tail2).

                        
                    

Assignment

Continue the Assignment

Read Day 3

Resources

  • http://www.lix.polytechnique.fr/~liberti/public/computing/prog/prolog/prolog-tutorial.html
  • http://www.cpp.edu/~jrfisher/www/prolog_tutorial/contents.html