Re: prolog program solutions

Michael Hauptmann <[email protected]>
Newsgroups gmane.comp.gnu.prolog.general
Message-ID <[email protected]>
 > Unfortunatelly I have never use this language
I recommend this (very good) free online book:
http://www.learnprolognow.org/lpnpage.php?pageid=online


I am not an expert, but here are my suggestions for your problems:
(The solutions are not difficult. The above mentioned book will help you 
to understand them.)


 > 1. Summary of the elements in a list,
 > and check that is divided or not diveded with 3?

Solution 1 of problem 1:

list_sum([], 0).
list_sum([L | Ls], Sum) :-
     list_sum(Ls, Sum_of_Ls),
     Sum is Sum_of_Ls + L.

list_sum_divisible_by_3(List) :-
     list_sum(List, Sum),
     0 is Sum mod 3.

The first solution is better readable, but the next solution is better 
for the stack because it is tail recursive:


Solution 2 of problem 1:

list_sum(List, Sum) :-
     list_sum_aux(List, 0, Sum).

list_sum_aux([], Accumulator, Accumulator).
list_sum_aux([L | Ls], Accumulator, Result) :-
     New_Accumulator is Accumulator + L,
     list_sum_aux(Ls, New_Accumulator, Result).

list_sum_divisible_by_3(List) :-
     list_sum(List, Sum),
     0 is Sum mod 3.


 > If the 7 is in a list, doubles it.

double_7(Input_List, Output_List) :-
     double_7_aux(Input_List, Output_List - []).

double_7_aux([], X-X).
double_7_aux([7 | Ls], [7, 7 | X] - Y) :-
     !,
     double_7_aux(Ls, X - Y).
double_7_aux([L | Ls], [L | X] - Y) :-
     double_7_aux(Ls, X - Y).


 > If the 7 is in a list, change it for 2,7,2.

This problem and the second problem are very similar.


 > What is the program and how to
 > test it with SWI-Prolog?
This is the GNU Prolog mailing list, but I would recommend:
• Read the above mentioned book.
• Read this section of the GNU Prolog Manual:
   http://www.gprolog.org/manual/gprolog.html#htoc8


Best Regard,
M. Hauptmann.

_______________________________________________
Users-prolog mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/users-prolog
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.