Home > Archive > Prolog > December 2004 > adding numbers
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
|
|
| Nelson Marcelino 2004-12-03, 9:01 pm |
| how can I add numbers define by facts?
eg.
n(1).
n(3).
n(5).
n(6).
add(N) :-
n(X),
N is N + X,
fail.
Does not seem to work...the answer I am looking for should be 1 + 3 + 5 + 6 = 15.
| |
| Markus Triska 2004-12-07, 4:13 am |
| Nelson Marcelino wrote:
> how can I add numbers define by facts?
Collect all answers into one list and then compute the sum of its elements:
n(1).
n(3).
n(5).
n(6).
list_sum(L,Sum) :-
list_sum(L,0,Sum).
list_sum([],S,S).
list_sum([E|Es],S1,S) :-
S2 is S1 + E,
list_sum(Es,S2,S).
thesum(Sum) :-
bagof(N,n(N),List),
list_sum(List,Sum).
Best regards,
Markus Triska.
| |
| Nelson Marcelino 2004-12-07, 4:13 am |
| Thanks for the reply Markus,
Just wondering is it possible to compute a summation using a recursive
predicate definition
without having to resort to the use of Lists?
Your help is greatly appreciated.
PS I'm finding prolog to be a better tool for many things than lisp,
or functional languages, such
as Ocaml, Haskell, SML, clean,etc.
Currently I am using SWI Prolog.
Can you recommend a good prolog for production grade code. SWI seems
like a very good product.
Best regards,
Nelson Marcelino
Markus Triska <triska@gmx.at> wrote in message news:<41b1cd63$0$11352$3b214f66@tunews.univie.ac.at>...
> Nelson Marcelino wrote:
>
>
> Collect all answers into one list and then compute the sum of its elements:
>
> n(1).
> n(3).
> n(5).
> n(6).
>
>
> list_sum(L,Sum) :-
> list_sum(L,0,Sum).
>
> list_sum([],S,S).
> list_sum([E|Es],S1,S) :-
> S2 is S1 + E,
> list_sum(Es,S2,S).
>
>
> thesum(Sum) :-
> bagof(N,n(N),List),
> list_sum(List,Sum).
>
>
> Best regards,
> Markus Triska.
| |
| Markus Triska 2004-12-07, 4:13 am |
| Nelson Marcelino wrote:
>
> Just wondering is it possible to compute a summation using a recursive
> predicate definition
> without having to resort to the use of Lists?
>
Sure, it's only a matter of convenience. If for example you are using
trees to represent sums,:
treesum(nil,0).
treesum(tr(Val,Left,Right),Sum) :-
treesum(Left,L),
treesum(Right,R),
Sum is L + R + Val.
However, in your case I see no advantage in avoiding bagof/3. (You can
surely rewrite the predicate yourself using forced backtracking and such.)
> Currently I am using SWI Prolog.
> Can you recommend a good prolog for production grade code. SWI seems
> like a very good product.
I have no experience with commercial implementations, so I'm afraid I
can't help you with these (I heard that SICStus is very good).
Personally, I'm mainly using SWI Prolog and find it a pleasure to work with.
Best regards,
Markus.
|
|
|
|
|