[plt-scheme] Doubt in folding

From: namekuseijin (namekuseijin at gmail.com)
Date: Fri Oct 23 13:39:11 EDT 2009

On Fri, Oct 23, 2009 at 1:55 AM, David Storrs <david.storrs at gmail.com> wrote:
> On Thu, Oct 22, 2009 at 3:24 PM, Eduardo Bellani <ebellani at gmail.com> wrote:
>> ;; my-fold-left : (X X -> X) X (listof X) -> (listof X)
>> ;; applies operation to each element of lox, and
>> ;; combines them in a new list. Works from left to right
>> ;; in lox.
>> (define (my-fold-left combinator initial lox)
>>  (local [(define (folding local-lox accumulator)
>>            (cond
>>              [(empty? local-lox) accumulator]
>>              [else
>>               (folding (rest local-lox)
>>                        (combinator (first local-lox)
>>                                    accumulator))]))]
>>    (folding lox initial)))
>>
>>
>> ;; plt's built in foldl
>> (foldl cons empty (list 1 2 3 4))         ; evals to (4 3 2 1)
>>
>> ;; mine
>> (my-fold-left cons empty (list 1 2 3 4))  ; evals to (4 3 2 1) thanks
>> for the hint!
>
>
> This version also works for the limited test cases I ran:
>
> (define (myfoldl comb init l)
>  (if (empty? l)
>      init
>      (myfoldl comb
>               (comb (car l) init)
>               (cdr l))))

of course that's the plain, simple and no-frills foldl in plain Scheme.


Posted on the users mailing list.