Wednesday 15 January 2014

recursion - My Scheme Function: How to Make it Recursive -



recursion - My Scheme Function: How to Make it Recursive -

so in scheme function, provided below, need produce list of structures. far, i've made 2 helper functions: 1 calls list of numbers counting 1 x. other calls construction corresponds x.

for example:

(helper1 10) -> (list 1 2 3 4 5 6 7 8 9 10) (helper2 1) -> (make-person 0 1) (helper2 2) -> (make-person 1 2) (helper2 3) -> (make-person 2 3) etc...

how can create main function phone call list of helper1, each element replaced corresponding structure.

note: main function must recursive, , must produce list of structures.

so far, main function have:

(define (main-function x) (cond [(zero? x) empty] [else ...]))

also, writing in beginner pupil list abbreviations.

you'll want build exclusively new list, not replace each element structure. that's appearance of end result, not how function works.

basically, if main-function takes in number, you'll want create helper function recursion, pass in result of calling (helper1 x).

then, in recursion, you're recontructing list corresponding structures.

(define (main-function x) (main-function-helper (helper1 x))) (define (main-function-helper l) (cond [(empty? l) l] [else (cons (helper2 (first l)) (main-function-helper (rest l)))]))

another alternative may create more sense never create intermediate list:

(define (main-function x) (main-function-helper 1 x)) (define (main-function-helper counter max) (cond [(= counter max) (cons (helper2 counter) empty)] [else (cons (helper2 counter) (main-function-helper (add1 counter) max))]))

recursion scheme racket

No comments:

Post a Comment