This page is available as PDF here.
Functions
Functions are first-class values in Epos, supporting higher-order functions, generics, and default parameters.
Basic Function Syntax
Functions use the fn
keyword (short for function) with
implicit returns (last expression is returned):
fn say-hello(name: string)
("Hello, #{name}!")
printend
fn add(a: int, b: int): int
+ b
a end
fn greet(name: string): string
"Hello, #{name}!"
end
fn multiply(x: int, y: int): int
* y
x end
Function Types
Functions are values and can be passed around:
# Function type syntax: fn(param_types) -> return_type
fn higher-order(f: fn(int, int) -> int, x: int, y: int): int
(x, y)
fend
# Use it
result: int = higher-order(add, 5, 3) # result is 8
Lambda Functions
Create anonymous functions using lambda syntax:
# Lambda with explicit type
= fn(x: int): int => x * x
square :
# Use lambdas with higher-order functions
= {1, 2, 3, 4, 5}
numbers := numbers.map(fn(x: int): int => x * x) squared :
Default Parameters
Functions can have default parameter values:
fn greet-with-title(name: string, title: string = "Mr."): string
"Hello, #{title} #{name}!"
end
# Call with default
= greet-with-title("Smith") # "Hello, Mr. Smith!"
greeting1 :
# Call with explicit value
= greet-with-title("Smith", "Dr.") # "Hello, Dr. Smith!" greeting2 :
Generic Functions
Write functions that work with any type:
fn identity(value: t): t
valueend
# Generic function with multiple type parameters
fn make-pair(first: a, second: b): Pair(a, b)
{
@=> first,
first => second
second }
end
# Usage
-age := make-pair("Alice", 30)
name= make-pair(10, 20) coords :
Higher-Order Functions
Functions that take or return other functions:
# Function that returns a function
fn make-adder(n: int): fn(int) => int
fn(x: int) => x + n
end
-five := make-adder(5)
add= add-five(10) # result is 15
result :
# Function composition
fn compose(f: fn(b) -> c, g: fn(a) -> b): fn(a) -> c
fn(x: a) => f(g(x))
end
Recursive Functions
Functions can call themselves:
fn factorial(n: int): int
<= 1 then
match n true => 1
false => n * factorial(n - 1)
end
end
fn fibonacci(n: int): int
match n then0, 1 => n
=> fibonacci(n - 1) + fibonacci(n - 2)
_ end
end
Built-in List Functions
Epos provides several built-in functions for working with lists:
numbers: list(int) = {1, 2, 3, 4, 5}
# Map: transform each element
= numbers.map(fn(x: int): int => x * 2)
doubled :
# Filter: select elements that match a predicate
= numbers.filter(fn(x: int): bool => x % 2 == 0)
evens :
# Each: iterate over list elements
.each(fn(x: int) => print(x))
numbers
# Length: get number of elements
= numbers.len()
count :
# Element access
= numbers.elem(0) first :
Type Aliases for Function Types
Make complex function types more readable:
Predicate(t) = fn(t) -> bool
type Transform(a, b) = fn(a) -> b
type BinaryOp(t) = fn(t, t) -> t
type
fn filter-with-predicate(items: list(t), pred: Predicate(t)): list(t)
(items, pred)
filterend
Next, learn about pattern matching in Epos.
Next page →