Elifant
2007-07-01 07:42:03 UTC
Hello all.
I propose to add functions like Haskell's foldr1 and foldl1 to standard
library. They are very convenient
when result has the same type and element type has no "zero" value with
respect to the applied operation.
Example:
Within macro call I have a list of expressions (with type PExpr) "e1,
e2, ..., eN" and I need to get expression
"((e1 + e2) + ...) + eN". FoldLeft can't be used directly, since <[]>
can't be used as a starting value.
With FoldLeft: def sum = FoldLeft(exprs.Tail, exprs.Head, (el, er) => <[
$el + $er ]>)
With FoldLeft1: def sum = FoldLeft1(exprs, (el, er) => <[ $el + $er ]>)
Don't know whether these functions must have a different name or just be
an overload of FoldLeft and FoldRight.
Reference implementation:
def FoldLeft1 ['a'] (l: list['a], f: 'a * 'a -> 'a): 'a
FoldLeft(l.Tail, l.Head, f)
// This one may be implemented more efficiently, I think...
def FoldRight1 ['a'] (l: list['a], f: 'a * 'a -> 'a): 'a
def (rest, last) = DivideLast(l)
FoldRight(rest, last, f)
I propose to add functions like Haskell's foldr1 and foldl1 to standard
library. They are very convenient
when result has the same type and element type has no "zero" value with
respect to the applied operation.
Example:
Within macro call I have a list of expressions (with type PExpr) "e1,
e2, ..., eN" and I need to get expression
"((e1 + e2) + ...) + eN". FoldLeft can't be used directly, since <[]>
can't be used as a starting value.
With FoldLeft: def sum = FoldLeft(exprs.Tail, exprs.Head, (el, er) => <[
$el + $er ]>)
With FoldLeft1: def sum = FoldLeft1(exprs, (el, er) => <[ $el + $er ]>)
Don't know whether these functions must have a different name or just be
an overload of FoldLeft and FoldRight.
Reference implementation:
def FoldLeft1 ['a'] (l: list['a], f: 'a * 'a -> 'a): 'a
FoldLeft(l.Tail, l.Head, f)
// This one may be implemented more efficiently, I think...
def FoldRight1 ['a'] (l: list['a], f: 'a * 'a -> 'a): 'a
def (rest, last) = DivideLast(l)
FoldRight(rest, last, f)