I am learning Prolog right now and I am trying to write a predicate newhead/3
that simply appends the second parameter to the first parameter that represents a list.
So newhead([1,2],3,R)
should yield R = [3,1,2].
I wrote the following and I am confused as to what this error message says as well as why the logic of my code does not seem to be correct.
newhead([H|T],E,R) :-
L is [H|T],
R is [E|L].
Or:
newhead(L,E,R) :-
R is [E|L].
Also doesn't work. This seems like it should be a pretty trivial operation but I can't believe that it could need recursion.
I appreciate any help.
您可以简单地写:
new_head(Tail, Head, [Head| Tail]).
You can use the predicate 'append/3'.
apped([3],[1,2],R).
R = [3,1,2]
or
append([X],[1,2],R), X=3.
R = [3,1,2]
I am sure that you already found your answer :) but I want to explain my answer too.
My understanding: first parameter is list and aim is the make the second argument head of the list.
Here is code:
new([],F,[F]). % if your list is empty.
new([X|XS],F,[F,X|XS]):-
new(XS,F,YS).
Output:
?- new([2,3],1,R).
R = [1, 2, 3].
?- new([],1,R).
R = [1].
?- new([2,3],[1],R).
R = [[1], 2, 3].
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.