Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Ovid (2709)

Ovid
  (email not shown publicly)
http://publius-ovidius.livejournal.com/
AOL IM: ovidperl (Add Buddy, Send Message)

Stuff with the Perl Foundation. A couple of patches in the Perl core. A few CPAN modules. That about sums it up.

Journal of Ovid (2709)

Monday May 16, 2005
01:31 AM

Hobbled. Solving Prolog Puzzles.

[ #24715 ]

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.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.