views:

250

answers:

2

Please help me with using the DrScheme built-in function "filter".

"create a function "hello" that consumes a number 'Max', and a list of numbers 'L', produce a list of numbers in 'L' that are smaller than 'Max'."

edit Taken from the comments for formatting

this is what i have so far

(define (smaller? n Max) 
  (cond 
    [(> Max n) n] 
    [else empty])) 
(define (hello Max L) 
  (filter smaller? L))

I don't know how to implement Max into the function hello.

A: 

Hint: You can create an anonymous function with lambda:

(lambda (x) (have-fun-with x))

edit: Another hint: (> Max n) already returns a boolean, you don't need an enclosing cond structure.

Svante
my problem is that im not sure how i can do it without using Max in the lambda
Ben
or rather, the predicate inside filter only consumes one thing, but i have two things, 'Max' and 'L', so i dont know how to work around that
Ben
If you use the lambda inside a function, it sees everything in that function's scope.
Svante
@Ben: You work around that by using a closure. Example: (lambda (foo) (lambda (bar) (+ foo bar))). The inner lambda can access the "foo" in the outer lambda. Hope that helps!
Chris Jester-Young
thank you guys, your discussion of closure really helped, i looked into it and found out what to do
Ben
and btw, (> Max n) is a good hint, thanx again
Ben
+1  A: 

Using your smaller? definition, I would go for something like

(define (hello Max L)
  (filter (lambda (n) (smaller? n Max)) L))

This uses a lambda function which is a closure over the Max argument to the hello function. So it "embeds" Max inside the lambda function used for filtering.

Kasprzol
Thank you for agreeing with me about what a closure is. :-)
Chris Jester-Young
Of course, the `smaller?` function is completely superfluous.
Svante
this is what i end up with in the end (define (hello Max L) (filter (smaller Max) L)) (define (smaller Max) (lambda (n) (< n Max)))
Ben
you are missing a right parenthesis
newacct
ah, true. updated the code.
Kasprzol