Question

Code in Prolog a predicate swapFirstTwo/2 that swaps the rst two elements of the given list....

Code in Prolog a predicate swapFirstTwo/2 that swaps the rst two elements of the given list.
If the list is too short, it must fail.
?- swapFirstTwo([a,b,c,d,e], Ys).
Ys = [b,a,c,d,e].
?- swapFirstTwo([a], Ys).
false.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The following is the required Prolog Predicate.

swapFirstTwo([A,B|T],[B,A|T]).

The answer seems really simple as the answer is actually very simple.

As you can see the functor here is swapFirstTwo/2 as instructed in the question, that is the predicate has an arity of 2.

The first argument here is [A,B|T] and the second argument is simply [B,A|T] , which simply means that it is the same list but with the first two elements swapped.

A and B represents the first and the second elements of the list respectively, and T represents the remaining elements of the list.

Also, the predicate will return false if the number of elements in the list is less than 2.

Note:- A, B and T needs to be in capital. This denotes that A,B and T are variables. if these characters are not written in capital the predicate would not work correctly.

Below is a list of some sample outputs:-

?- swapFirstTwo([],Ys).
false.

?- swapFirstTwo([a],Ys).
false.

?- swapFirstTwo([z],Ys).
false.

?- swapFirstTwo([a,b],Ys).
Ys = [b, a].

?- swapFirstTwo([a,1],Ys).
Ys = [1, a].

?- swapFirstTwo([a,1,b],Ys).
Ys = [1, a, b].

?- swapFirstTwo([2,1,b],Ys).
Ys = [1, 2, b].

?- swapFirstTwo([a,b,c,d,e],Ys).
Ys = [b, a, c, d, e].

?- swapFirstTwo([x,y,z,a,b],Ys).
Ys = [y, x, z, a, b].

?- swapFirstTwo([&,1,z,a,b],Ys).
Ys = [1, &, z, a, b].

If you have any query regarding the answer let me know in the comment section, I would love to help.

Add a comment
Know the answer?
Add Answer to:
Code in Prolog a predicate swapFirstTwo/2 that swaps the rst two elements of the given list....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT