[plt-scheme] How to do something to all element of a list but the last
I'm not sure, but that definition might require O(n^2) time. (Try
timing it and seeing ...)
This is how I'd write it but I'm old fashioned when it comes to little
loops like these. (And I didn't run the code. here's hoping no typos.)
#lang scheme
(provide/contract
[foo (-> (cons/c any/c (listof any/c))
(-> any/c any)
(-> any/c void?)
void?)])
(define (foo args fun last-fun)
(let loop ([fst (car args)]
[rst (cdr args)])
(cond
[(empty? rst) (last-fun fst)]
[else (fun fst) (loop (car rst) (cdr rst))])))
Robby
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
>
>