1
votes

this is the second part of a question on a paradigms exam paper that I'm currently working my way through and it's got me a bit stumped, but then I'm still quite a prolog noob so the solution is probably obvious..

I wrote this rule/fact contains1(X, [X|_]). for checking if the given element is equal to the head of the given list. This is fine, it works as expected and from all my reading I'm maybe 95% sure that's the best way to go about it. But then the question also says to write a prolog query using this rule to display the first element in a given list.

I'm using swi-prolog to enter and test all my rules etc and the only way I know how to get it to display the first element of a given list is with the query [H|T] = (some_list). So how exactly do I work my rule into this..? Any help or a point in the right direction would be much appreciated, cheers.

1

1 Answers

1
votes

Make prolog find out what value of X makes the clause valid:

contains(X, sample_list).

For example,

contains(X, [1, 2, 3]).

will return X = 1, because when X = 1, then the clause is true.

Remember that, when given a clause like this, Prolog will try to look for all values of X such that that clause becomes true.