# take

(define (take n xs) (cond ((<= n 0) '()) ((null? xs) '()) (else (cons (car xs) (take (- n 1) (cdr xs))))))

fun take ([], _) = [] | take (x::xs, i) = if i>0 then x::take(xs, i-1) else [];

Constant-space, tail-recursive, with accumulator-passing-style. The second *clause* looks like a partial helper function.

fun take ([], _, acc) = acc | take (x::xs, i, acc) = if i>0 then take (xs, i-1, x::acc) else rev acc; (* this rev makes it O2N, but constant factors don't matter *)

take n _ | n <= 0 = [] take _ [] = [] take n (x:xs) = x : take (n-1) xs

take m ys = case (m,ys) of (0,_) -> [] (_,[]) -> [] (n,x:xs) -> x : take (n-1) xs

Last modified
16 months ago
Last modified on Oct 24, 2018, 9:58:03 AM

**Note:**See TracWiki for help on using the wiki.