[plt-scheme] what is fold-left?

From: Andreas Rottmann (a.rottmann at gmx.at)
Date: Wed Feb 11 23:46:05 EST 2009

Mike Eggleston <mikeegg1 at me.com> writes:

> On Wed, 11 Feb 2009, Mike Eggleston might have said:
>
>> Morning,
>> 
>> I'm looking at some code at
>> <http://funcall.blogspot.com/2007/08/naive-bayesian-classifier.html>. This
>> code by default will not run in DrScheme. The code is using (fold-left
>> ...). Looking at the function it looks like a (map ...), but I don't
>> (yet) know why I can't just use a 'map' instead of the 'fold-left'.
>> 
>> Any ideas? What does this function do that 'map' doesn't and why
>> should it be used?
>> 
>> Mike
>
> I found a reference here:
>
> <http://docs.plt-scheme.org/r6rs-lib-std/r6rs-lib-Z-H-4.html#node_idx_212>
>
> How to I call this library? I'm using '#lang scheme' as the first
> line of my file.
>
Using '#lang scheme':

#lang scheme

(require scheme/mpair
         rnrs/lists-6)

(display (fold-left cons '() (list->mlist '(2 3 6 1))))
(newline)

; EOF

Note the a bit awkward use of `list->mlist' from scheme/mpair
necessitated by the fact that PLT's default language and R[56]RS are
incompatible when it comes to pairs: R6RS gives you mutable pairs
(although you need to import `(rnrs mutable-pairs)' to get `set-car!'
and `set-cdr!'), whereas PLT gives you immutable pairs, which you have
to convert from/to mutable pairs when taking or giving values from/to
R6RS libraries.

Another option would be to switch to R6RS completely (which would
probably make sense for the example program, as it seems to be aimed at
R6RS in the first place), like this:

#!r6rs

(import (rnrs base)
        (rnrs io simple)
        (rnrs lists))

(display (fold-left cons '() '(2 3 6 1)))
(newline)

; EOF

Note that the (in both programs) is not a list, but `((((() . 2) . 3)
. 6) . 1)', as R6RS `fold-left' has the accumulator on the left side, as
opposed to SRFI-1 and PLT. With the second program, the output is `{{{{()
. 2} . 3} . 6} . 1}', as mutable pairs are displayed with curly brackets
by default, and R6RS `cons' returns mutable pairs.

Regards, Rotty



Posted on the users mailing list.