Functional Library: A Symphony of Data

Cast the net of your thoughts into the river of data. Higher-order functions like map, filter, and reduce abstract away repetitive tasks and elegantly sculpt the flow of data. Code becomes concise, and thought becomes clear.

This page provides a reference for the core higher-order functions in Lispex. These functions take other functions as arguments to process lists, enabling a powerful and declarative programming style.


map

Applies a given function to every element in a list and returns a new list containing the results. The new list will always have the same number of elements as the original list.

  • Syntax: (map FUNCTION LIST)
  • Arguments:
    • FUNCTION: A function that takes one argument (the list element) and returns a transformed value.
    • LIST: The list to iterate over.
  • Returns: A new list containing the transformed elements.
  • Throws: A RuntimeError if the arguments are not a function and a list respectively.

Example:

;; Create a new list with each number squared.
(map (lambda (n) (* n n)) (list 1 2 3 4))
;; Result: (list 1 4 9 16)

filter

Returns a new list containing only the elements from the original list for which a given predicate function returns a truthy value (anything other than #f).

  • Syntax: (filter PREDICATE_FUNCTION LIST)
  • Arguments:
    • PREDICATE_FUNCTION: A function that takes one argument and returns a boolean (#t to keep the element, #f to discard it).
    • LIST: The list to filter.
  • Returns: A new list, which may be shorter than or the same length as the original.
  • Throws: A RuntimeError if the arguments are not a function and a list respectively.

Example:

;; Create a new list with only numbers greater than 5.
(filter (lambda (n) (> n 5)) (list 2 8 4 10 5 7))
;; Result: (list 8 10 7)

reduce

Reduces a list to a single value by repeatedly applying a function. It iterates through the list, maintaining an "accumulator" that is updated at each step.

  • Syntax: (reduce FUNCTION INITIAL_VALUE LIST)
  • Arguments:
    • FUNCTION: A function that takes two arguments: (accumulator, current_element). It should return the new value of the accumulator.
    • INITIAL_VALUE: The starting value for the accumulator.
    • LIST: The list to reduce.
  • Returns: The final value of the accumulator after iterating through the entire list.
  • Throws: A RuntimeError if the arguments are not a function, a value, and a list.

Example: Summing all numbers in a list

(reduce (lambda (sum el) (+ sum el))
        0
        (list 10 20 30 40))
;; Result: 100

Example: Finding the longest word in a list

(reduce (lambda (longest word)
          (if (> (length word) (length longest))
              word
              longest))
        ""
        (list "Lispex" "is" "a" "delightful" "language"))
;; Result: "delightful"