-1

So I'm having trouble trying to obtain a single element from a list using Prolog without using recursion, only relying on loops, such as foreach, foreachelem, etc....

So I have a list Xs = [1,2,3], and I want to obtain each element individually. The best I've come up so far is this...

sumOfList(Xs, Max) :-
    ( foreach(List, Xs), count(I, 1, _), param(Xs)
         do
            ( foreach(List2, Xs), count(J, 2, _), param(Xs, I, List)
                do
                   ( List =< List2
                     -> Max is List2;
                     Max is List1
                   )
            )
    ).

This is the best I've got so far... So I'm wondering, how do I create some kind of placeholder for Max that can be used for the final calculation?

Sergii Dymchenko
  • 6,890
  • 1
  • 21
  • 46

1 Answers1

4

Your question is not very clear for me. That's how you can find the max in the list of non-negative elements with ECLiPSe declarative loops:

max_with_loop(Xs, Max) :-
    ( foreach(Xi, Xs), fromto(0, MaxPrev, MaxCurr, Max) do
        MaxCurr is max(MaxPrev, Xi) ).

The interesting part is fromto(0, MaxPrev, MaxCurr, Max). Using this part you can transmit information between iterations. Initially MaxPrev becomes 0, after each iteration MaxCurr becomes MaxPrev, after the loop MaxCurr becomes Max.

BTW, declarative loops in ECLiPSe are kind of syntactic sugar, they are translated to recursive calls by the system.

Update: variant, suggested by @false in the comments, that also works with negative numbers:

max_with_loop([First | Xs], Max) :-
    ( foreach(Xi, Xs), fromto(First, MaxPrev, MaxCurr, Max) do
        MaxCurr is max(MaxPrev, Xi) ).
Sergii Dymchenko
  • 6,890
  • 1
  • 21
  • 46