[plt-scheme] How to do something to all element of a list but the last

From: Ethan Herdrick (info at reatlas.com)
Date: Sat Aug 9 15:10:24 EDT 2008

Hi Grant:

You should always start with the functional programming approach:

(require (lib "1.ss" "srfi"))

(for-each (λ (x) (printf "Got: ~a~n" x))
     (drop-right '(1 2 3 4) 1))


The key here is "drop-right".  In general, manipulate your list first,
then it's map (or for-each), filter, or sometimes fold.  Repeat as
necessary.

Hope this is helps.

-Ethan

2008/8/7 Grant Rettke <grettke at acm.org>:
> Hi folks,
>
> While reviewing some code I wrote a while back, I found 'do' used in
> many places. On further review, I found that this use of 'do' doesn't
> qualify as "there was no better way" but more like "when I wrote it I
> didn't know any other way".
>
> The usage is like that of 'for-each', but for the fact that different
> functionality is executed depending on whether or not the element
> being processed is the last element of the list, or not.
>
> Is there a "best way" to do something like this?
>
> I haven't thought too much into this because I am too tired, but, I
> did come up with this for the fun of it. I will think about it more
> tomorrow.
>
> #lang scheme
>
> (define (foo args fun last-fun)
>  (match args
>    [(list arg args ..1)
>       (fun arg)
>       (foo args fun last-fun)]
>    [(list arg)
>       (last-fun arg)]))
>
> (foo '(a b c d e)
>       (λ (x) (printf "Got: ~a~n" x))
>       (λ (x) (printf "Last One: ~a~n" x)))
>
> Best wishes,
>
> Grant
>
> _________________________________________________
>  For list-related administrative tasks:
>  http://list.cs.brown.edu/mailman/listinfo/plt-scheme
>
>

Posted on the users mailing list.