RacketSchemeFunctional-ProgrammingLambda

Higher-Order Functions in Racket | Schema Programming Part 5

3.97 min read
Md Nasim SheikhMd Nasim Sheikh
Share:

In functional programming, functions are values. This means you can pass them around just like numbers or strings. Functions that take other functions as input or return them as output are called Higher-Order Functions (HOFs).

Advertisement

The Big Three: Map, Filter, Fold

These three functions are the bread and butter of list processing in Racket.

1. Map

map applies a function to every element in a list and returns a new list of the results.

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

(map square '(1 2 3 4))
; Result: '(1 4 9 16)

2. Filter

filter keeps only the elements that satisfy a predicate (a function that returns true/false).

(define (is-even? x) (= (remainder x 2) 0))

(filter is-even? '(1 2 3 4 5))
; Result: '(2 4)

3. Fold (Reduce)

foldl (fold left) and foldr (fold right) combine all elements of a list into a single value using a combining function.

; Sum of a list
(foldl + 0 '(1 2 3 4))
; Result: 10
; Calculation: (+ 4 (+ 3 (+ 2 (+ 1 0)))) roughly

Note: foldl is generally preferred in Racket as it is tail-recursive and constant space.

Anonymous Functions: lambda

Often, you don't want to define a named function like square just to use it once. Enter lambda.

(map (lambda (x) (* x x)) '(1 2 3 4))
; Result: '(1 4 9 16)

A lambda expression creates a function without a name. Syntax: (lambda (arguments) body)

Closures

A closure is a function that "remembers" the environment in which it was created. This allows for powerful data hiding and factory patterns.

(define (make-adder n)
  (lambda (x) (+ x n)))

(define add5 (make-adder 5))
(add5 10) ; 15

Here, add5 is a function that "closes over" the value n=5.

Advertisement

Composition

You can combine simple functions to build complex ones.

(define (square-even-numbers lst)
  (map (lambda (x) (* x x))
       (filter even? lst)))

(square-even-numbers '(1 2 3 4 5))
; Result: '(4 16)

Summary

  • Map: Transform a list.
  • Filter: Select elements from a list.
  • Fold: Summarize a list.
  • Lambda: Create quick, throwaway functions.
  • Closures: Functions with memory.

In the next part, we will look at one of Racket's most distinguishing features: Macros.

Quick Quiz

Which function would you use to remove all negative numbers from a list?

Md Nasim Sheikh
Written by

Md Nasim Sheikh

Software Developer at softexForge

Verified Author150+ Projects
Published:

You May Also Like