0
votes

I am new to Prolog and wanted to start learning the functionality of [H|T] by trying to write the prefix function on my own. The prefix function returns all possible prefixes to a list, such as for L = [a,b,c] would be [], [a], [a,b] and [a,b,c]. I am confused about how my own Prolog function would be able to return so many different solutions. I have it splitting the head and tail of the list, and appending the head to my new list that is going to be the different prefixes returned. This is what I have so far, but I think I am oversimplifying, and don't know how else to recursively call it to get all the different possibilities.

myPrefix([],[]). 

myPrefix([H|T],List) :- myPrefix(T, [H|List]).

I looked at a lot of the other answers, but those just deal with getting the first element off of a list, not listing all possible prefixes. Any advice of how to go from here or more explanation as to how this head and tail of list manipulation functionality works is appreciated.

1

1 Answers

2
votes

Assuming the first argument if instantiated is indeed is a proper list, then this should do it:

myPrefix(_, []).
myPrefix([H|T], [H|NT]):-
  myPrefix(T, NT).

First clause ignores the first argument and unifies the second with the empty list.

Second clause takes the head of first argument list and puts it as the head of the second argument, and calls itself recursively.

So in effect, the second clause takes one by one as many items as desired and the first clause drops the tail.