Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Summing. I'm still living in imperative land.

4 views
Skip to first unread message

Chui Tey

unread,
Sep 24, 2007, 12:21:27 AM9/24/07
to
Hi all,

I've got a program here:

% different sized nuts in the toolbox
t(1).
t(2).
t(4).

% build a list of nuts
ts([]).
ts([t(H)|Ts]) :- ts(Ts), t(H).

% get sum of nut sizes after
% arranging nuts as a palindrome
go(SumOfH):-
length(Ts, 3),
ts(Ts),
reverse(Ts, Ts),
findall(H, (t(H), memberchk(t(H), Ts)), Hs),
sumlist(Hs, SumOfH),
display(Ts).

The question is: is there a simpler way to do this without memberchk?
memberchk seems awfully redundant.

Markus Triska

unread,
Sep 24, 2007, 1:36:17 AM9/24/07
to
Chui Tey <te...@cognoware.com> writes:

> ts([t(H)|Ts]) :- ts(Ts), t(H).

Why carry the t/1 functor with you? Just collect the sizes, like:

ts([T|Ts]) :- ts(Ts), t(T).

> display(Ts).

You want a relation sum_nuts/2 between a sum S and a list of
palindromic nut sizes summing to S. If you define just that, the
toplevel will handle display for you.

--
comp.lang.prolog FAQ: http://www.logic.at/prolog/faq/

Chui Tey

unread,
Sep 24, 2007, 2:18:46 AM9/24/07
to
On Sep 24, 3:36 pm, Markus Triska <tri...@logic.at> wrote:

> Chui Tey <t...@cognoware.com> writes:
> > ts([t(H)|Ts]) :- ts(Ts), t(H).
>
> Why carry the t/1 functor with you? Just collect the sizes, like:
>
> ts([T|Ts]) :- ts(Ts), t(T).
>

I was trying to do this (Python equivalent, apologies):

# height, thickness, size of the head
nuts = [(5, 10, 2),
(8, 10, 3), ...]

nuts_sublist = foo(nuts) #
total_height = sum([nut[0] for nut in nuts_sublist])
total_thickness = sum([nut[1] for nut in nuts_sublist])
etc...

I don't want to rebuild nuts_sublist to calculate each statistic. It's
hard learning to talk another language!

Markus Triska

unread,
Sep 24, 2007, 2:54:53 AM9/24/07
to
Chui Tey <te...@cognoware.com> writes:

> total_height = sum([nut[0] for nut in nuts_sublist])

Suppose Sub = [t(5,10,2),t(8,10,3)], then:

?- maplist(arg(1), $Sub, Hs), sumlist(Hs, TotalH).
%@ Hs = [5, 8],
%@ TotalH = 13

> total_thickness = sum([nut[1] for nut in nuts_sublist])

?- maplist(arg(2), $Sub, Ts), sumlist(Ts, TotalT).
%@ Ts = [10, 10],
%@ TotalT = 20

Chui Tey

unread,
Sep 24, 2007, 6:51:00 AM9/24/07
to

> ?- maplist(arg(2), $Sub, Ts), sumlist(Ts, TotalT).
> %@ Ts = [10, 10],
> %@ TotalT = 20

Thanks! arg/3 is exactly what I was looking for!

0 new messages