1

I'm having a little trouble understanding list recursion and modification in Prolog. I'm trying to take a list of lists, then with each list, multiply each element in the list by the last element.

Here's a snippet of my code:

    /*Find the last element of a list*/
    lastelement(X,[X]).
    lastelement(X,[_|L]) :- lastelement(X,L).

    /*Multiply two lists together*/
    multiplication(M1,M2,M1*M2).

    /*Take a list, find the last element and multiply every part of that list by that  element*/
    /*Attach modified list to X*/
    modifyL([],X) :- X is [].
    modifyL([First|Tset],X) :- lastelement(Y,First),
    multiplication(Y,First,MFirst),
    modifyL([Tset],X),
    append(X,MFirst,X).

When I try any list of lists, however, all I get is false. Can someone give me any pointers on list recursion that could help further understand this problem?

2
  • which implementation are you using? Commented Feb 10, 2013 at 20:46
  • I'm currently using SWI Prolog version 5.10 Commented Feb 10, 2013 at 20:47

1 Answer 1

1
modifyL([],X) :- X is [].

This doesn't do what you think, is is used to get the result of an arithmetic evaluation.

you can write

 modifyL([],X) :- X = [].

or simply

 modifyL([],[]).

When you work with a list, and you repeat the same process to each element of this list you can use maplist which is exactly design for that. the template is maplist(Goal, L1 L2).

modify(L1, L2) :-
  maplist(multiply_one_list,L1, L2).

multiply_one_list works with a list, you it can be written like that :

multiply_one_list(L_in, L_out) :-
  % getting last argument
  reverse(L_in, [Last | _]),
  % multiply each element of the list by
  % the last element, one more maplist !
  maplist(multiply_one_element(Last), L_in, L_out).

multiply_one_element(Last, In, Out) :-
  Out is In * Last.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks alot, this got me back on track.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.