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

From: Grant Rettke (grettke at acm.org)
Date: Fri Aug 8 00:29:22 EDT 2008

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

Posted on the users mailing list.