Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

interweaved let and cond

0 views
Skip to first unread message

Bell Foster

unread,
Mar 8, 2006, 5:22:25 AM3/8/06
to
Recently I've encountered a situation where I wondered about let and
cond working together. The problem in broad terms is this:

if a list is null do something
else if the first item of a list equals something, do something else
else if the first item equals this other thing, do this other thing
else if the first item equals yet another another, do yet another
different thing.
and so on

Writing the cond:
(cond ( (null? some-list) do-something)
( (= foo (car some-list)) do-something-else)
( (= bah (car some-list)) do-this-other-thing)
( (= baz (car some-list)) yet-another-thing)
( etc. for several cases

It's really redundant to write "car some-list" for each case, and it
could get worse if in the next problem I want something with even
longer notation than car.

And a let can't be used here, because it can't be intertwined with a
cond statement.

So I thought of breaking the cond into an if and a cond, with a let
around the cond, like:

if (null? some-list)
do-something
(let ( (first-item (car some-list)))
(cond ( (= first-item foo) whatever)
..and so on with the cond

And I began to wonder if this if/cond structuring is the standard way
to handle this, or if experts know more than I.

Jens Axel Søgaard

unread,
Mar 8, 2006, 5:53:06 AM3/8/06
to

Variations of both approaches are widespread. In some situations
one can take advantage of specialized constructs. E.g.

(if (null? a-list)
<do-something>
(case (car a-list)])
[(foo) <do-something1>]
[(bar) <do-something2>]
[(baz) <do-something3>])

Mixing binding and cond can be cumbersome. Pattern matching
is often clearer. Your example becomes

(match a-list
[() <do-something>]
[('foo . _) <do-something1>]
[('bar . _) <do-something2>]
[('baz . _) <do-something3>])

which isn't that much of an improvement, but in more complicated
situations the advantage is greater.

--
Jens Axel Søgaard

Bell Foster

unread,
Mar 8, 2006, 2:57:36 PM3/8/06
to

> Variations of both approaches are widespread. In some situations
> one can take advantage of specialized constructs. E.g.
>
> (if (null? a-list)
> <do-something>
> (case (car a-list)])
> [(foo) <do-something1>]
> [(bar) <do-something2>]
> [(baz) <do-something3>])
>
> Mixing binding and cond can be cumbersome. Pattern matching
> is often clearer. Your example becomes
>
> (match a-list
> [() <do-something>]
> [('foo . _) <do-something1>]
> [('bar . _) <do-something2>]
> [('baz . _) <do-something3>])
>
> which isn't that much of an improvement, but in more complicated
> situations the advantage is greater.

Thanks, I'm glad that there isn't some super obvious solution which I
was missing.

0 new messages