Functions in Scheme: Defining and Calling Functions

July 9, 2024

Explore the concept of functions in Scheme in this lesson. Understand how to define functions, pass arguments, and return values. Learn about higher-order functions and recursion in Scheme.

Defining Functions

In Scheme, functions are defined using the (define (function-name parameters) body) syntax. Here’s an example of a simple function that adds two numbers:

(define (add x y) (+ x y))

This function is named add and takes two parameters x and y. It returns the sum of the two parameters.

Calling Functions

To call a function in Scheme, you simply write the function name followed by the arguments enclosed in parentheses. For example, to call the add function defined above:

(add 5 3)

This will return 8, the sum of 5 and 3.

Returning Values

In Scheme, functions implicitly return the value of the last expression evaluated. You can also explicitly return a value using the return keyword. Here’s an example:

(define (square x) (return (* x x)))

This function named square takes one parameter x and returns the square of x.

Higher-Order Functions

Higher-order functions in Scheme are functions that can take other functions as arguments or return functions as results. This functional programming feature allows for powerful abstractions and concise code. Here’s an example of a higher-order function:

(define (apply-twice f x) (f (f x)))

The apply-twice function takes a function f and a value x, then applies f twice to x.

Recursion

Recursion is a common technique in Scheme where a function calls itself. This allows for elegant solutions to problems that can be naturally defined recursively. Here’s an example of a recursive function to calculate the factorial of a number:

(define (factorial n) (if (< n 2) 1 (* n (factorial (- n 1)))))

The factorial function calculates the factorial of n by recursively multiplying n with the factorial of n-1 until n is less than 2.