[eclipse-users] GetLastOne, an alternative

From: kot23 <kot23_at_...97...>
Date: Sun, 10 Feb 2008 22:12:19 +0200
Hello everyone,

Dimitris Bilidas wrote:
>...
 > The problem I have now is how to get the last position of an element
> with a specific value from a list with uninstantiated variables. What I want to
> do is to get the position of the last 1, from a list of which all elements must
> be either 0 or 1.
 > ...
> getLastOne1(List, Res):-
> M#=length(List),
> (foreach(E,List), for(I,1,M), foreach(T,Temp) do
> T #= I*E),
> Res#=max(Temp).

I would suggest the following:
The list could be split in two parts: the part before the last "1" (Part1) and the part after the last "1" (Part2). The sum of Part2 should be 0, since all elements after the last "1" are "0"s. The Result would be the length of Part1, plus one.
This could be coded as follows:

getLastOne3(List, Result) :-
	append(Part1, [1|Part2], List),
	ic_global:sumlist(Part2, 0),
	Result is length(Part1) +1.

and it must be invoked using the infers/2 predicate from lib(propia):

?- L = [A, B, C, D, E], L :: 0 .. 1, getLastOne3(L, Pos) infers ic, D = 1.
L = [A{[0, 1]}, B{[0, 1]}, C{[0, 1]}, 1, E{[0, 1]}]
A = A{[0, 1]}
B = B{[0, 1]}
C = C{[0, 1]}
D = 1
E = E{[0, 1]}
Pos = Pos{[4, 5]}
There is 1 delayed goal.
Yes (0.00s cpu)

Now, I understand that using infers/2 may be slower but i think it is a more declarative and elegant way to represent what we look for. Any thoughts on that, anyone?

-- 
kot23_at_...97...
Received on Sun Feb 10 2008 - 20:12:23 CET

This archive was generated by hypermail 2.3.0 : Tue Apr 16 2024 - 09:13:20 CEST