[plt-scheme] creating nested lists in DrScheme

From: Aniket Karmarkar (akarmarkar at mail.bradley.edu)
Date: Sat May 8 12:47:44 EDT 2010

Thanks. Atleast I can get a nested list now.... Will ask again if I am still
stuck.


On Sat, May 8, 2010 at 9:42 AM, Stephen Bloch <sbloch at adelphi.edu> wrote:

>
> On May 7, 2010, at 11:55 PM, Aniket Karmarkar wrote:
>
> That's what this function does:
> (define (equal L1 L2)
>   (cond
>     ((eq? (caar L1) (car L2)) (car L1))
>     (else (equal (cdr L1) L2))
>   )
> )
>
> This function find the sublist which match. I had it before but I forgot to
> include it. So it returns (b c d). I tried the map function but you need the
> arguments to have same number in both arguments. :(
>
>
> There's a standard trick to get around that.
>
> Suppose I want to make a list of the two-element lists ' (a x), '(b x), '(c
> x), '(d x).  I'm doing the same thing to each element of the list '(a b c
> d), and producing a list of the results, so "map" seems like the right tool.
>  What is it that I want to do to each of these elements?  Create a pair with
> that element and x.  So I write a function
> (define (pair-with-x something)
>     (list something x))
> then call
> (map pair-with-x '(a b c d))
>
> Sound good so far?  It has a problem: it only works if you have a FIXED x
> that you can hard-code into the "pair-with-x" function.  If the thing you
> want to combine with is a parameter, or has just been computed, or something
> like that, you define "pair-with-x" LOCALLY:
>
> (define (pair-with-a-b-c-d x)
>    (define (pair-with-x something) (list something x))
>    (map pair-with-x '(a b c d)))
>
> Make sense?
>
> Now, a brief digression.  Suppose you wanted to compute 3+4*5.  One way to
> do it would be in two steps:
> (define temp (* 4 5))
> (+ 3 temp)
> But if the only reason for having "temp" is to use it in one subsequent
> expression, why bother giving it a name?  It's shorter and simpler to say
> (+ 3 (* 4 5))
>
> Similarly, Scheme allows you to define a function without bothering to give
> it a name, if you're just going to use it once, using "lambda".
>
> (define (pair-with-a-b-c-d x)
>    (map (lambda (something) (list something x)) '(a b c d)))
>
> In general, anything you can do with a local definition can also be done
> with lambda, possibly shorter, and anything you can do with lambda can also
> be done with a local definition, possibly clearer (if you like having names
> for things).
>
> Hope that helps!
>
>
> Stephen Bloch
> sbloch at adelphi.edu
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20100508/9a859296/attachment.html>

Posted on the users mailing list.