简体   繁体   中英

Scheme/Racket filter/map multiple arguments

Lets say I want to do the following:

(define (foo lst x)
   (filter function lst)

but function takes in 2 arguments (and function was given to me), one being the list lst it will use, and the other being x . Syntactically, how would I change that line to pass in the second argument? Sorry I am new to Scheme/DrRacket.

Try this, using curry :

(define (foo lst x)
   (filter (curry function x) lst))

That is, assuming that function takes as first parameter x and as second parameter each one of the elements in lst . In other words, the above is equivalent to this:

(define (foo lst x)
  (filter (lambda (e) (function x e))
          lst))

Either way: the trick (called currying ) is to create a new function that receives a single argument, and passes it to the original function, which has the other argument fixed with the given x value.

In your question, it's not clear in which order we should pass the arguments, but once you understand the basic principle at work here, you'll be able to figure it out.

The simplest is:

(define (foo ys x)
   (filter (λ (y) (function y x)) ys)

An alternative:

(define (foo ys x)
   (for/list                    ; collect results into a list
      ([y ys]]                  ; for each element y in the list ys
        #:when (function y x))  ;   when (function y x) collect
      x))                             x

Or without comments:

 (define (foo ys x)
   (for/list ([y ys]] #:when (function y x))
      x)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM