43 lines
1.0 KiB
Plaintext
43 lines
1.0 KiB
Plaintext
// Demonstrating functional programming features
|
|
|
|
// Higher-order functions
|
|
fn apply(f: fn(Int): Int, x: Int): Int = f(x)
|
|
|
|
fn compose(f: fn(Int): Int, g: fn(Int): Int): fn(Int): Int =
|
|
fn(x: Int): Int => f(g(x))
|
|
|
|
// Basic functions
|
|
fn double(x: Int): Int = x * 2
|
|
fn addOne(x: Int): Int = x + 1
|
|
fn square(x: Int): Int = x * x
|
|
|
|
// Using apply
|
|
let result1 = apply(double, 21) // 42
|
|
|
|
// Using compose
|
|
let doubleAndAddOne = compose(addOne, double)
|
|
let result2 = doubleAndAddOne(5) // 11
|
|
|
|
// Using the pipe operator
|
|
let result3 = 5 |> double |> addOne |> square // ((5 * 2) + 1)^2 = 121
|
|
|
|
// Currying example
|
|
fn add(a: Int): fn(Int): Int =
|
|
fn(b: Int): Int => a + b
|
|
|
|
let add5 = add(5)
|
|
let result4 = add5(10) // 15
|
|
|
|
// Partial application simulation
|
|
fn multiply(a: Int, b: Int): Int = a * b
|
|
|
|
let times3 = fn(x: Int): Int => multiply(3, x)
|
|
let result5 = times3(7) // 21
|
|
|
|
// Working with records
|
|
let transform = fn(record: { x: Int, y: Int }): Int =>
|
|
record.x + record.y
|
|
|
|
let point = { x: 10, y: 20 }
|
|
let sum = transform(point) // 30
|