Article View: comp.lang.prolog
Article #1932Re: simple question
From: Bill Viggers
Date: Wed, 20 Mar 1991 22:50
Date: Wed, 20 Mar 1991 22:50
96 lines
2431 bytes
2431 bytes
For starters its easiest if you give Prolog functions, names that
describe what they do. Personally I also dislike
have two functions with the same name and different arity.
Thus your program could be re-written as:
writeln(S):-
write(S),
nl.
makelist:-
writeln('Enter the verticies'),
getlist(List),
write(List).
getlist(L):-
read(Item),
addtolist(Item,List).
addtolist(end,_):-!.
addtolist(Item,List):-
List=[Item|List],
writeln('Another one...'),
getlist(List).
Now it is clearer what is happening.
The first time though an item is got, and the list is set equal to it.
The second time though, another item is got, and then the line:
List=[Item|List],
is executed, and it will fail as List is not equal to the new item
followed by the previous item.
An example:
| ?-makelist.
Enter the verticies
|: 3.
Another one...
|: 4.
no
We can se getlist is called, it reads 3, and calls addtolist
addtolist sets List equal to [3], then sends that list on to another
call to getlist. This time getlist reads a 4, and sends that, along
with the current list to addtolist. Addtolist trys to set
[3] = [4|3].
Which it fails to do.
A solution then could be:
writeln(String):-
write(String),
nl.
makelist:-
writeln('Enter the verticies'),
getlist(List),
write(List).
getlist(Thelist):-
read(Item),
addtolist(Item,_,Thelist).
addtolist(end,_,end):-!.
addtolist(Item,List,Thelist):-
Thelist=[Item|List],
writeln('Another one...'),
getlist(List).
This returns a list, with the last item being an 'end'
eg:
| ?- makelist.
Enter the verticies
|: bill.
Another one...
|: viggers.
Another one...
|: end.
[bill,viggers|end]
yes
I hope this helps.
B.
Technical Details
Message-ID:
<1991Mar20.225013.21372@comp.vuw.ac.nz>Path:
arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!swrinde!elroy.jpl.nasa.gov!decwrl!waikato.ac.nz!comp.vuw.ac.nz!billReferences:
<WAYNE.91Mar19112927@offa.cs.odu.edu>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!swrinde!elroy.jpl.nasa.gov!decwrl!waikato.ac.nz!comp.vuw.ac.nz!bill From: Bill.Viggers@comp.vuw.ac.nz (Bill Viggers) Newsgroups: comp.lang.prolog Subject: Re: simple question Message-ID: <1991Mar20.225013.21372@comp.vuw.ac.nz> Date: 20 Mar 91 22:50:13 GMT References: <WAYNE.91Mar19112927@offa.cs.odu.edu> Sender: news@comp.vuw.ac.nz (News Admin) Organization: Computer Science, Victoria University, Wellington, NewZealand Lines: 96 Nntp-Posting-Host: embassy.comp.vuw.ac.nz Originator: bill@embassy.comp.vuw.ac.nz