2

Looking for advice. I'm adding foldl1/3 and foldr1/3 meta-predicates to the Logtalk library. These can be easily defined:

foldl1(Closure, [Head| Tail], Result) :-
    foldl(Closure, Head, Tail, Result).

foldr1(Closure, [Head| Tail], Result) :-
    foldr1_(Tail, Head, Closure, _, Result).

foldr1_([], Result, _, Result, Result).
foldr1_([Arg2| Args], Arg1, Closure, Acc, Result) :-
    foldr1_(Args, Arg2, Closure, Acc, Acc2),
    call(Closure, Arg1, Acc2, Result).

With these definitions, calling the meta-predicates with an empty list simply fail. But this doesn't allow distinguish from the case where the call fails due to one of the implicit goals constructed from the closure failing.

If you envision yourself using these meta-predicates, do you find failure on empty lists an acceptable behavior or would you prefer an exception being generated in this case?

false
  • 10,264
  • 13
  • 101
  • 209
Paulo Moura
  • 18,373
  • 3
  • 23
  • 33
  • 1
    Failure on empty lists is acceptable to me if one can just use `foldr/5` and `foldl/5` to handle empty lists. – Daniel Lyons Dec 02 '15 at 00:35
  • 1
    @DanielLyons The versions that take an accumulator or initial value, `foldl/4` and `foldr/4`, are already available and those are defined for empty lists. – Paulo Moura Dec 02 '15 at 00:38
  • Then it sounds great. :) – Daniel Lyons Dec 02 '15 at 00:42
  • 2
    Most of the time, I only use fold (not fold1). So I would push the decision (fail with nil or raise exn) on to the user. – repeat Dec 02 '15 at 07:08
  • 1
    @repeat There also other similar cases that only makes sense for non-empty lists in the library, e.g. `numberlist::min/2` and `numberlist::max/2`, that also fail on empty lists. Committed. Thanks to you and Daniel for the feedback. – Paulo Moura Dec 02 '15 at 11:02

0 Answers0