Functions in Racket
Our first program will demonstrate functions in Racket. Here’s the full source code:
In this example, we define two functions: plus
and plus-plus
.
The plus
function takes two parameters a
and b
, and returns their sum. In Racket, the last expression in a function is automatically returned, so we don’t need an explicit return statement.
The plus-plus
function demonstrates how to define a function with multiple parameters. In Racket, you simply list all the parameters you need.
In the main
function, we call these functions and print their results. Racket uses prefix notation for function calls, so we write (plus 1 2)
instead of plus(1, 2)
.
To run this program, save it as functions.rkt
and use the racket
command:
Racket is a functional programming language, so functions are first-class citizens. This means you can pass functions as arguments, return them from other functions, and assign them to variables. This opens up many powerful programming techniques that we’ll explore in later examples.