Hobbled. Solving Prolog Puzzles.

Ovid on 2005-05-16T06:31:41

Being laid up with a bad foot, I decided to work through more of the Amzi! Prolog tutorial. I really like the tutorial as it's clearly written and show how things operate under the hood. I read the lists chapter to see if I could learn techniques to better explain lists. Unfortunately, they are something that you'll either get or your won't. However, working through each of the exercises is like solving a bunch of mini-logic puzzles. I like that.

Here's my stab at various questions (they can be harder than they look, but as is often the case, a simpler answer is more likely to be correct).

  • Remove a given element from a list
    remove(X,[X|Tail],Tail).
    remove(X,[Head|Tail],[Head|Remainder]) :-
        remove(X,Tail,Remainder).
  • Find the element after a given element
    next(X,[X|[Y|_]],Y).
    next(X,[_|Tail],Y) :-
        next(X,Tail,Y).
  • Split a list into two lists at a given element (this is really simple, but I made it very complicated at first)
    split(X,List, Before, After) :-
        append(Before, [X|After],List).
  • Get the last element of a list (isn
    last([X],X).
    last([_|Tail],X) :- last(Tail,X).
  • Count the elements in a list
    length([],0).
    length([_|TAIL],N) :-
        length(TAIL,N1),
        N is N1 + 1.

That last one was tricky because the math must be done last to ensure the N1 variable is instantiated since math is not done logically in Prolog.