Functions in Racket

Our first program will demonstrate functions in Racket. Here’s the full source code:

#lang racket

; Here's a function that takes two numbers and returns their sum
(define (plus a b)
  (+ a b))

; When you have multiple parameters, you can simply list them
(define (plus-plus a b c)
  (+ a b c))

; The main function where we'll call our defined functions
(define (main)
  ; Call a function just as you'd expect, with (name args)
  (let ([res (plus 1 2)])
    (printf "1+2 = ~a\n" res))
  
  (let ([res (plus-plus 1 2 3)])
    (printf "1+2+3 = ~a\n" res)))

; Call the main function
(main)

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 functions.rkt
1+2 = 3
1+2+3 = 6

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.