views:

161

answers:

3

How do I pass position-independent parameters to scheme functions?

A: 

I am not a scheme guru, but I'm thinking that parameters need to be a pair rather than an atom, then you make a parameter list from your pairs and use a let block to bind the values to actual parameters. And, for the love of all that is beautiful, call a helper function to do the actual work with the parameters in the right order since calling get-param in recursion is going to get expensive.

(define get-param (lambda (name pair-list)
    (cond ((null? pair-list) nil)
          ((eq? name (caar pair-list)) (cadr (car pair-list)))
          (t (get-param name (cdr pair-list))))))

; position independent subtract always subtracts y from x
; usage (f '(x 7) '(y 9)) => -2
;       (f '(y 9) '(x 7)) => -2
(define f (lambda (x-pair y-pair)
    (let ((pl (list x-pair y-pair))
        (let ((x (get-param 'x pl)) (y (get-param 'y pl))
            (- x y)))))

Someone who is really clever would make a factory function that would take an arbitrary lambda expression and build an equivalent position independent lambda from it.

plinth
+2  A: 

In PLT Scheme you can use:

(define area
   (lambda (x #:width y)
     (* x y)))

(area 3 #:width 10)

or

(area #:width 10 3)

both would return 30.

mamboking
Is there a way to change this? I know my named parameters are same as the one being used. (define (foo #:a a #:b b #:c c) (+ a c))(foo #:a 1 #:b 0 #:c 10)
kunjaan
+1  A: 

There's no standard support for this in scheme but have a look at this

Paul Hollingsworth