user1768884
user1768884

Reputation: 1037

Prolog: take a list of two elements, return true if and only if the first element is same as second

I'm a newbie prolog programmer, and for an assignment, I have to have a basic program that succeeds if and only if list X is a list of two elements, with the first as the same as the second.

From my view of prolog, programs seem to be pretty small, so I typed this in:

firstPair(x,x).

When I run it under swipl, I get this as output:

Syntax error: Operator expected

Is there something more that needs to be done? I thought that if I executed this with say, firstPair(1,2). this would be all it would need to know that it is false.

Upvotes: 0

Views: 1448

Answers (2)

Nicholas Carey
Nicholas Carey

Reputation: 74187

Your program/fact

firstPair(X,X).

will succeed if the two arguments given it can be unified, whether they are lists, atoms, variables, etc. To meet your specification, a

program that succeeds if and only if list X is a list of two elements, with the first as the same as the second.

You need something like this:

list_of_two_elements( [X,X] ).

This will succeed if passed a single term that is (or can be unified with) a list of two elements that are, or can be made through unification, identical. For instance, all of the following will succeed:

  • list_of_two_elements( X ).

    on success, the variable X will be unified with a list of two elements containing the same unbound variable, something like [V1,V1].

  • list_of_two_elements( [1,1] ).

  • list_of-two_elements( [1,X] ). (on success, X here will have been unified with the integer 1.)

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

First, lowercase x is not a variable, it's an atom. Make x uppercase to fix the problem:

firstPair(X,X).

Second, you do not type this into the interpreter. Rather, you write it into a file firstPair.pl, and then read that file into Prolog.

At the command prompt, type this:

['firstPair.pl'].

Press enter. Now you can use your firstPair/2 rule.

Finally, since the assignment talks about lists, I think the instructor wanted you to write firstPair/1, not firstPair/2:

firstPair([X,X]).

Upvotes: 3

Related Questions