tadashi
tadashi

Reputation: 91

Define a function as argument and passing a number in Racket

I'm trying to define a function as an argument and then passing a number to that function. It should look like this:

> (function-3 sqrt)

1.7320508075688772

I was thinking of just defining function-3 to equal to 3 but it seems like it doesn't work... this is what I have so far:

(define function-3
   (λ (x)
     (3)))

I don't know if I'm thinking on the right path...but it would be great if someone can just point me in the right direction. Thanks

Upvotes: 4

Views: 5614

Answers (2)

Alexis King
Alexis King

Reputation: 43842

You’re close—you just want to apply the argument of function-3 to the number 3, like this:

(define function-3
  (λ (x)
    (x 3)))

More idiomatically, using the shorthand function syntax, it would probably be written like this:

(define (function-3 f)
  (f 3))

(The name f is often used instead of x when the value is a function.)


But why?

Functions in Racket (as in its parent language, Scheme) are just ordinary values. Behind all the parentheses, the syntax for function application is actually extremely simple. Here’s an example scheme expression:

                 (f a b c)
                  ^ ^^^^^
                  |   |
function expression   argument expressions

Note that each of these two roles is an expression. Obviously, the arguments can be expressions, not just variables, since you can do things like this:

> (+ 1 (* 2 3))
7

Notably, though, the function itself can be an expression, too. You can have a form that produces a function, and that expression can be used in a function invocation:

> ((λ (x) (* x 2)) 3)
6

So when you call (function-3 sqrt), the sqrt function itself gets passed into the function and bound to the first argument of the function implementation. Therefore, all you need to do is put that argument in function expression position, and it will be invoked like any other function.

Upvotes: 9

C. K. Young
C. K. Young

Reputation: 223003

You're so close!

(define function-3
  (lambda (x)
    (x 3)))

Upvotes: 5

Related Questions