1

I'm starting to learn Prolog, but I cannot find any examples on what I want to do: a list that contains several other lists; is it possible?

Something like this: [ [1,1,1], [2,2,2], [3,3,3] ].

Thank you in advance.

3
  • 2
    yes, a list is a term, and terms are defined recursively (you can nest them as you like) Commented May 19, 2015 at 21:58
  • 1
    That said, don't overuse lists. Commented May 19, 2015 at 22:45
  • But the problem is, I don't know how to make a nested list, I find prolog really hard to understand with all the recursivity...how I hate that <.< Commented May 19, 2015 at 22:52

3 Answers 3

3

Try typing at the prompt X = [ [1,1,1], [2,2,2], [3,3,3] ].. Prolog will type it back to you -- i.e. it accepts this as a valid input.

The following are all different ways to specify the same list X:

    X = [ [1,1,1], [2,2,2], [3,3,3] ].
    X = [ [1,1,1], [2,2,2] | [ [3,3,3] ] ].
    X = [ [1,1,1] | [ [2,2,2], [3,3,3] ] ].
    A = [1,1,1], X = [A | [ [2,2,2], [3,3,3] ] ].
    A = [1,1,1], B = [ [2,2,2], [3,3,3] ], X = [A | B].
    A = [1 | T], T = [1,1], B = [ [2,2,2], [3,3,3] ], X = [A | B].
    T = [1,1], B = [ [2,2,2], [3,3,3] ], X = [A | B], A = [1 | T].

This shows how to construct the lists by bits and pieces. No "recursivity" required for that, just plain specification and construction; or construction and specification, the order does not matter.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice explanation! Even better would be to ensure that they are the same, too.
No mistake! My comment was just how to best present this to a beginner who should be able to add his own equations. So how can a beginner learn to know that they are all the same? And what exactly means "the same"? Evidently, only the initial variables should remain the same, auxiliary variables are permitted etc.etc.
1

OK so I managed to do the following:

?- findall([NAME,POST,TIMEFLIGHT], pilot(_,NAME,POST,_,_,TIMEFLIGHT,_), Xs),
   show(Xs).

show([]):-!.
show([Head|Tail]):-
   write(Head),nl,
   show(Tail).

which gives me what I wanted, wich is this:

Xs = [ [Joe, Pilot, 100], [Stan, Co-Pilot, 300], [Steve, Pilot, 150] ].

1 Comment

Sorry, I'll edit and post another question accordingly.
0

Prolog is very "open mind" in what is a list. Some examples of list and methods to define a list:

?- X=[1,[a]].
X = [1, [a]].

?- X='.'(1,[2]).
X = [1, 2].

?- X=[1|foo].
X = [1|foo].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.