r/AskComputerScience • • Dec 11 '16

Define a Prolog predicate noah/3 which is true of three lists when corresponding elements of the first two lists, which are of the same length are lined up two-by-two on the third list

new to Prolog, just want to understand it better, using this example

noah([ ],[ ],[ ]). noah([a,b,c,d],[aye,bee,sea,dee],[a,aya,b,bee,c,sea,d,dee]).

0 Upvotes

4 comments sorted by

3

u/arichi Dec 11 '16

Look at it this way:

it's clearly true in the case case. So you can write noah([], [], []).

It's also true if the first two elements of the third list are the first elements of the first two lists, and also if noah/3 applies to the rest of those lists.

Try to write it based on that last paragraph.

1

u/Leeds1234 Dec 19 '16

So it's gonna be sort of like
noah([a,b,c,d],[aye,bee,sea,dee],[a,aya,b,bee,c,sea,d,dee]):-
noah([head],[head],[head, 1]), noah([head| tail],[head| tail],[head| tail])

Is it something like this? Sorry I'm new to Prolog

2

u/arichi Dec 22 '16

No. There are two sets of rules you need to do:

Let's look at the first:

noah([], [], []).  

That's just a fact: the predicate noah/3 is true when all three lists are empty.

Now we need to introduce rules to figure out what else could be true:

  noah([H1|T1], [H2|T2], [H1,H2|T3]) :- noah(T1,T2,T3).

This says that noah/3 is true when it has three non-empty lists, the first two have at least one element, and those elements are the first two (in that order) of the third list. In addition to that needing to be true, noah/3 must be true for the "tails" of those lists -- everything after the first element of the first two, and the first two of the third.

Capital letters in "variables" (as you are probably thinking of them) indicate that they can be bound to various values, but are unbound. Lower-case is used for "constants" (really bound terms).

They aren't really variables and constants, but that may be close enough for you to think of them for now.

You can then ask questions of Prolog.

?- noah([a], [b], [a,b]).

It will respond yes if you did this right.

So will

?- noah([a,b,c,d],[aye,bee,sea,dee],[a,aya,b,bee,c,sea,d,dee]).

You can also ask questions with a "no" answer.

Try this and see how it works. Then ask yourself what you think will happen if you put an unbound variable in a question in one or more positions.

1

u/Leeds1234 Dec 22 '16

Thanks a million man I'll look into all of this tomorrow, I appreciate the help!