Reputation:
Write a Scheme procedure named 'proc4' which takes 2 procedures as arguments (w,x) [note that w and x can be expected to work correctly when given two numbers as arguments] and returns a procedure which takes 2 numbers (y,z) as arguments and returns the procedure (w or x) which results in the greatest number when applied to y and z (i.e. in C++ pseudocode if ((y w z) > (y x z)) {return w; } else {return x;} )
So I started
(define proc4(lamdda ( w x) (lambda y z)... Then I wanted to do the if part. Something like (if (> (apply w ( y z)) (apply x( w z))) but I keep getting errors.
I've been trying to find help on internet but everything I've seen so far does not make sense to me.
Upvotes: 1
Views: 372
Reputation: 235984
A bit of syntactic sugar for @ChrisJester-Young's answer - you can declare a procedure that returns another procedure like this:
(define ((proc4 f g) x y)
(if (> (f x y) (g x y))
f
g))
In the above code, the first procedure receives as parameters the procedures f
and g
, and in turn returns a procedure that receives as parameters x
and y
. We know that f
and g
are procedures because the way they're used inside the body of the definition, but they can have any name you want. Of course you can call the procedure in the usual way:
((proc4 + *) 10 20)
=> #<procedure:*>
The point of interest in this example is that procedures can also be passed as parameters (and returned as values), you don't need to apply
them, just invoke the procedures received as parameters as you would with any other procedure. Also notice that all the answers to this question are equivalent, but the short-hand syntax that I'm using might not be available in all interpreters.
Upvotes: 1
Reputation: 18917
I cannot make much sense of this (obviously homework) question but I'd go for this:
(define proc4
(lambda (w x)
(lambda (y z)
(if (> (w y z) (x y z))
w
x))))
Upvotes: 0
Reputation: 222973
You can invoke function objects directly, without using apply
:
(define (proc4 f g)
(lambda (x y)
(if (> (f x y) (g x y))
f
g)))
Upvotes: 2