Map Function
The Expected Output:How it works:
map function applies a transformation to every element in a list:higher_order.elr
maptakes a functionf : (a -> b)and a list of typea- It applies
fto each element, producing a list of typeb \x -> x * xis a lambda (anonymous function) that squares its input- The function is polymorphic - works with any types
aandb
The
>> operator sequences IO actions, similar to ; in imperative languages.Filter Function
The Expected Output:How it works:
filter function keeps only elements that satisfy a predicate:filtertakes a predicatep : (a -> Bool)and a list- It keeps elements where
preturnsTrue \x -> x > 3is a lambda that checks if a number is greater than 3- Combining
mapandfilterallows powerful data transformations
Generic Utility Functions
Higher-order functions can express common patterns:Expected Output:Function Explanations:
generics.elr
identity: Returns its argument unchanged- Type:
a -> a(polymorphic) - Useful for generic programming
const: Returns its first argument, ignoring the second- Type:
a -> b -> a alwaysTenis a partially applied function that always returns 10
flip: Reverses the order of arguments to a two-argument function- Type:
(a -> b -> c) -> b -> a -> c flip subchangessub x y(x - y) to subtract in the opposite orderflippedSub 10 4computes4 - 10 = -6
Combining Higher-Order Functions
The real power comes from composing higher-order functions:More Complex Example:Expected Output:Key Benefits:
- Declarative: express what you want, not how to compute it
- Reusable:
mapandfilterwork with any types and predicates - Composable: combine simple functions to create complex transformations
Common Higher-Order Functions
map
Transform each element in a collection
filter
Keep only elements that satisfy a condition
fold
Reduce a collection to a single value
compose
Combine multiple functions into one
Lambda Syntax
Elara uses backslash notation for anonymous functions:Multi-argument lambdas are automatically converted to nested single-argument lambdas during compilation (currying).
Next Steps
- Data Types - Define custom types to use with higher-order functions
- Recursion - Many higher-order functions are implemented recursively