forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06_higher_order.nula
More file actions
53 lines (45 loc) · 1.83 KB
/
Copy path06_higher_order.nula
File metadata and controls
53 lines (45 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// 06_higher_order.nula - Higher-order functions
// Demonstrates: functions as arguments, closures, function composition,
// closure factories, and transforming data with functions
//
// Run: nulang examples/06_higher_order.nula
// Apply a function twice
let twice = fn(f, x) {
f(f(x))
}
let inc = fn(n) { n + 1 }
let double = fn(n) { n * 2 }
perform IO.print("twice(inc, 5) = " + perform Int.to_string(twice(inc, 5)))
perform IO.print("twice(double, 3) = " + perform Int.to_string(twice(double, 3)))
// Function composition
let compose = fn(f, g, x) {
f(g(x))
}
let square = fn(n) { n * n }
let add_ten = fn(n) { n + 10 }
perform IO.print("sq(add10(5)) = " + perform Int.to_string(compose(square, add_ten, 5)))
perform IO.print("add10(sq(5)) = " + perform Int.to_string(compose(add_ten, square, 5)))
// Function that returns a function (closure factory)
let make_adder = fn(n) {
fn(x) { x + n }
}
let add5 = make_adder(5)
let add100 = make_adder(100)
perform IO.print("add5(10) = " + perform Int.to_string(add5(10)))
perform IO.print("add100(10) = " + perform Int.to_string(add100(10)))
// Higher-order conditional transformer
let apply_if = fn(pred, f, x) {
if pred(x) then f(x) else x
}
let is_even = fn(n) { n % 2 == 0 }
let triple = fn(n) { n * 3 }
perform IO.print("apply_if(even,triple,2) = " + perform Int.to_string(apply_if(is_even, triple, 2)))
perform IO.print("apply_if(even,triple,3) = " + perform Int.to_string(apply_if(is_even, triple, 3)))
// Recursive sum with a transformation function
let rec sum_with = fn(arr, idx, n, f) {
if idx >= n then 0
else f(arr[idx]) + sum_with(arr, idx + 1, n, f)
}
let nums = [1, 2, 3, 4, 5]
perform IO.print("sum(sq, [1..5]) = " + perform Int.to_string(sum_with(nums, 0, 5, square)))
perform IO.print("sum(double, [1..5]) = " + perform Int.to_string(sum_with(nums, 0, 5, double)))