Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'define' in Scheme

I'm new to Scheme and was just curious about 'define'. I've seen things like: (define (square x) (* x x)) which makes sense [Function name 'square' input parameter 'x']. However, I found some example code from the 90's and am trying to make sense of: (define (play-loop-iter strat0 strat1 count history0 history1 limit) (~Code for function~) Except for the function name, are all of those input parameters?

like image 423
V1rtua1An0ma1y Avatar asked Dec 26 '22 05:12

V1rtua1An0ma1y


1 Answers

Short answer - yes, all the symbols after the first one are parameters for the procedure (the first one being the procedures's name). Also it's good to point out that this:

(define (f x y)
  (+ x y))

Is just syntactic sugar for this, and both forms are equivalent:

(define f
  (lambda (x y)
    (+ x y)))

In general - you use the special form define for binding a name to a value, that value can be any data type available, including in particular functions (lambdas).

A bit more about parameters and procedure definitions - it's good to know that the . notation can be used for defining procedures with a variable number of arguments, for example:

(define (f . x) ; here `x` is a list with all the parameters
  (apply + x))

(f 1 2 3 4 5)   ; 0 or more parameters can be passed
=> 15

And one final trick with define (not available in all interpreters, but works in Racket). A quick shortcut for defining procedures that return procedures, like this one:

(define (f x)
  (lambda (y)
    (+ x y)))

... Which is equivalent to this, shorter syntax:

(define ((f x) y)
  (+ x y))

((f 1) 2)
=> 3
like image 136
Óscar López Avatar answered Jan 10 '23 05:01

Óscar López