[plt-scheme] idiomatic way to split a list into first, middle, last?

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Fri Jan 6 10:20:47 EST 2006

Jens Axel Søgaard wrote:

>   (define (map/last f f-last xs)
>     (list-ec (:pairs p xs)
>              ((if (null? (cdr p)) f-last f)
>               (car p))))
> 
>   (map/last + - (list 1 2 3 4 5))
>   ; => (1 2 3 4 -5)
> 
> which is reasonably readable, although I too would
> prefer your extension wish for match.

Without srfi-42 at all, one could write:

(define (pair-map f xs)
   (if (null? xs)
       '()
       (cons (f xs)
             (pair-map f (cdr xs)))))

(define (map/last f f-last xs)
   (pair-map (lambda (p)
               ((if (null? (cdr p)) f-last f)
                (car p)))
             xs))

(map/last + - (list 1 2 3 4 5))
; => (list 1 2 3 4 -5)

-- 
Jens Axel Søgaard





Posted on the users mailing list.