Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing in a binary function into a Scheme function

Apologies if this is a common question. Searching up "Racket passing in lambda as an argument" doesn’t return much. I’m trying to write a Racket function lsf that takes in an optional lambda function, and applies it to corresponding elements in two same-sized lists. This lambda defaults to addition.

For example, > (lsf '(2 4 5) '(6 7 8) (lambda (a b) (- b a))) should return a list '(4 3 3)

> (lsf '(2 5) '(3 6)) returns '(5 11) (defaults to addition).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s what I have so far:

( define ( lsf list1 list2 )
    ( if ( null? list1 )
        '()
        ( cons( + ( car list1 list2 )) 
            ( lsf ( cdr list1 ) ( cdr list2 )))
    )
)

How do I add this default addition function as a parameter (I think it goes after list2?), and how would I use it in place of the "+" that I have after cons?

>Solution :

Use . in the parameter list to define a rest-arg, which gets a list of all the additional arguments. If the optional argument is supplied, this will be non-null and you can get the argument as its first element.

(define (lsf list1 list2 . rest)
  (if (null? list1)
      '()
      (let ((func (if (null? rest) + (first rest)))) ; default func to +
        (cons (func (car list1) (car list2))
              (lsf (cdr list1) (cdr list2) func)))))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading