I'm very new to Prolog (coming from C++) and am having trouble understanding using lists as parameters. In particular, I am wondering how to account for the case in which a list only has one element (the tail is "empty"). Why can't I have [L] as a parameter by itself? Why must a tail be explicitly included?
/** Trying to print out the head of the list */
writeList([L|_]) :- write(L). /** Works fine */
writeList([L]) :- write(L). /** Doesn't work. Will return false, but why? */
writeList([L]) :- write([L]). /** I thought I'd try this to see if it was a
problem with write(), but this returns false as well. */
The only way solution I came up with (without creating tests after the ":-") was:
writeList([L|[]]) :- write(L).
But it seems a bit messy to have to specify the tail is []. Is there any cleaner way to do this?
Sorry if this question is very silly--I've tried to find an answer to this (quite basic) question but I suspect there's a problem in my fundamental understanding here.
The notation [X|Y] refers to a list whose first element is X and whose tail is Y.
The underscore _ is an anonymous variable and means any term. That's not what you want in this case.
A one-element list have an empty tail, so Y is bound to an empty list [], then the notation is: [X|[]]
In a similar way, for a two-element list: [X,Y|[]]
Check this Prolog Lists tutorial for more on this topic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With