users-prolog
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: prolog program solutions


From: Michael Hauptmann
Subject: Re: prolog program solutions
Date: Sat, 02 Jun 2012 00:07:54 +0200
User-agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.1.8) Gecko/20100227 Thunderbird/3.0.3

> 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.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]