Thursday 15 May 2014

scheme - How do you use dotted-tail notation correctly in this algorithm? -



scheme - How do you use dotted-tail notation correctly in this algorithm? -

i'm doing exercises sicp (not homework) , exercise 2.20 introduces dotted-tail notation, utilize (define (f . b) ...) pass variable number of arguments (which end in list b). problem in particular wants procedure takes integer a , returns list of arguments parity equal a's. problem not difficult; here solution:

(define (same-parity . b); int, b number of int arguments (let ((parity (remainder 2))) (define (proc li) (cond ((null? li) null) ; if parity of head of list = parity of a, ((= (remainder (car li) 2) parity) ; maintain , check rest of list. (cons (car li) (proc (cdr li)))) ; otherwise ignore , check rest of list. (else (proc (cdr li))))) (cons (proc b))))

my question don't seem using dotted-tail feature @ all. might have accepted 2 arguments, number , list; i'm wrapping algorithm in procedure proc away dotted-tail thing.

before wrote solution, wanted have recursive phone call resembling

(same-parity . (cdr b))

or spiritually similar, no matter how tried it, kept passing lists of lists or procedures or whatever. because don't know exactly . does, want (the racket docs didn't clear either). sum up,

is solution intended exercise, or there way utilize dot notation (which seems point of exercise) in algorithm?

you can't utilize (same-parity . (cdr b)) (since read in (same-parity cdr b)), can utilize (apply same-parity (cdr b)). that's how "splat" list arguments.

however, "inner procedure" approach had more efficient, there less list copying going on.

scheme racket variadic-functions sicp

No comments:

Post a Comment