scheme - Replicate Function -


i'm trying rewrite code function replicate repeats first item of list n times , returns list repeated first item , rest of list. here original function:

(check-expect (replicateone 1 '(stays same)) '(stays same)) (check-expect (replicateone 0 '(hello bye)) '(bye)) (check-expect (replicateone 3      '(repeat second third ))               '(repeat repeat repeat second third))  (define (replicateone n nonemptylist)   (cond [(zero? n) (rest nonemptylist)]         [else      (cons (first nonemptylist) (replicateone (sub1 n) nonemptylist))])) 

this have right now, it's not working.

(define (iterate f n x)   (cond     [(zero? n) x]     [else (iterate f (sub1 n) (f x))]))  (define (replicateone n nonemptylist)  (iterate (λ (x) (list x x)) n nonemptylist)) 

i'm trying in isl+ without recursion, i'm unsure how write iterate function using new techniques. feel use foldr, i'm not sure.

any great since i'm still learning.

thank you

here's how i'd iterate:

(define (replicateone n lst)   (iterate (lambda (x) (cons (first lst) x)) n (rest lst))) 

here's "an" implementation of iterate doesn't use direct recursion , run correctly isl+, but, it's (intentionally) obfuscated. you'll have fun trying figure out how works. ;-)

(define (iterate f n x)   (foldl (compose f second list) x (make-list n #f))) 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -