Scheme car and cdr recursion -


can explain me how recursion works in following function? specifically, interested in happens when function reaches base case. also, why named let used in code? (i not familiar named lets)

(define (unzip list-of-pairs)   (if (null? list-of-pairs)    (cons '() '())    (let ((unzipped (unzip (cdr list-of-pairs))))          (cons (cons (car (car list-of-pairs)) (car unzipped))                (cons (cdr (car list-of-pairs)) (cdr unzipped)))))) 

the procedure shown doesn't have special it, you're iterating on list of form:

'((1 . 2) (3 . 4) (5 . 6)) 

the "weird" part output building two lists instead of usual single list. know, when we're building single list output base case this:

(if (null? lst) '() ...) 

but here, given we're simultaneously building 2 lists, base case looks this:

(if (null? lst) (cons '() '()) ...) 

the code in question not using named let, it's plain old garden-variety let, there's nothing special it. it's useful because want call recursion once, given need obtain 2 values recursive call.

if don't mind being inefficient, procedure can written without using let, @ cost of calling recursion 2 times @ each step:

(define (unzip list-of-pairs)   (if (null? list-of-pairs)       (cons '() '())       (cons (cons (car (car list-of-pairs))                   (car (unzip (cdr list-of-pairs))))             (cons (cdr (car list-of-pairs))                   (cdr (unzip (cdr list-of-pairs))))))) 

of course, advantage of using let avoids double recursive call.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -