scheme - fetch n-elements from a list Racket -


how can fetch n-elements list, know first, rest etc, if want first 3 elements in list,

i.e (get-first 3 (list 1 2 3 4 5 6)) -> (list 1 2 3)

(get-first 5 (list 54 33 2 12 11 2 1 22 3 44)) -> (list 54 33 2 12 11)

this not homework, code me complete bigger picture of assignment, stuck , need few hints. not allowed use lambda or build-list , no recursion, somehow need b able map, filter, foldr etc...

as mentioned @alexisking, can use take procedure that's built-in in racket:

(take '(1 2 3 4 5 6) 3) => '(1 2 3)  (take '(54 33 2 12 11 2 1 22 3 44) 5) => '(54 33 2 12 11) 

if reason that's not allowed can still roll own version using higher-order procedures , no explicit recursion, do notice not using lambda impossible, allowed procedures mention (map, filter, foldr) all receive a lambda as parameter, , anyway all procedures in scheme lambdas under hood.

here's contrived solution, passing accumulator remembers in index we're in input list while traversing it, , building output list in cdr part. can't done without using lambda, if bothers see there, extract helper procedure , pass along:

(define (get-first n lst)   (reverse    (cdr     (foldr (lambda (e acc)              (if (= (car acc) n)                  acc                  (cons (add1 (car acc))                        (cons e (cdr acc)))))            '(0 . ())            (reverse lst))))) 

it still works expected, never such complicated thing when built-in procedure same:

(get-first 3 '(1 2 3 4 5 6)) => '(1 2 3)  (get-first 5 '(54 33 2 12 11 2 1 22 3 44)) => '(54 33 2 12 11) 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -