问题
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.
回答1:
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.
回答2:
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)))
来源:https://stackoverflow.com/questions/32728131/scheme-racket-filter-map-multiple-arguments