[racket] question about foldl implementation

From: Will Kurt (wckurt at gmail.com)
Date: Thu Aug 12 21:53:21 EDT 2010

For a presentation I'm working on I've been implementing various higher
order functions in javascript.

When trying to work out the proper foldl implementation I came across
something interesting in Racket

> (foldl cons '() '(1 2 3 4))
(4 3 2 1)

> (foldl - 0 '(1 2 3 4))
2

However when I looked into various other implementations of foldl I came
across very different behavior
Haskell's foldl seems to be implemented like this:
;;haskell-like definition
(define (foldl-haskell func accum lst)
  (if (null? lst)
      accum
      (foldl-haskell func (func accum (car lst)) (cdr lst))))

and yields these results:
> (foldl-haskell cons '() '(1 2 3 4))
((((() . 1) . 2) . 3) . 4)
> (foldl-haskell - 0 '(1 2 3 4))
-10
>

Unsure which was correct I broke out SICP which uses this definition:
;;sicp version
(define (fold-left op initial sequence)
  (define (iter result rest)
    (if (null? rest)
        result
        (iter (op result (car rest))
              (cdr rest))))
  (iter initial sequence))

with these results (same as the haskell-like version):
> (fold-left cons '() '(1 2 3 4))
((((() . 1) . 2) . 3) . 4)
> (fold-left - 0 '(1 2 3 4))
-10
>

So which of these is the canonical implementation of a left fold? Why the
difference in Racket?
For pure aesthetics I like the behavior of Racket in the case of cons, but
for '-' the others seems to make more sense.

Any insight into this is greatly appreciated!

Thanks!
--Will Kurt
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20100812/f21e0eeb/attachment.html>

Posted on the users mailing list.