-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambdas.praia
More file actions
66 lines (56 loc) · 1.63 KB
/
lambdas.praia
File metadata and controls
66 lines (56 loc) · 1.63 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
54
55
56
57
58
59
60
61
62
63
64
65
66
// ── Basic lambdas ──
let double = lam{ x in x * 2 }
let add = lam{ a, b in a + b }
print("double(5):", double(5))
print("add(3, 4):", add(3, 4))
// ── No params ──
let greet = lam{ in print("hello from lambda!") }
greet()
// ── Passing lambdas to functions ──
func apply(f, x) {
return f(x)
}
print("apply:", apply(lam{ x in x * x }, 7))
// ── Filter/map with pipes ──
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let evens = nums |> filter(lam{ n in n % 2 == 0 })
print("evens:", evens)
let squares = nums |> map(lam{ n in n * n })
print("squares:", squares)
// ── Chaining — reads top to bottom instead of inside out ──
let result = nums
|> filter(lam{ n in n > 5 })
|> map(lam{ n in n * 10 })
print("filtered & mapped:", result)
// ── Closures work ──
func makeMultiplier(factor) {
return lam{ x in x * factor }
}
let triple = makeMultiplier(3)
let times10 = makeMultiplier(10)
print("triple(5):", triple(5))
print("times10(5):", times10(5))
// ── Multi-line lambda ──
let process = lam{ x, y in
let sum = x + y
let product = x * y
return {sum: sum, product: product}
}
let r = process(3, 4)
print("sum:", r.sum, "product:", r.product)
// ── Lambda in a map ──
let actions = {
double: lam{ x in x * 2 },
negate: lam{ x in -x },
greet: lam{ name in "hello %{name}" }
}
print(actions.double(21))
print(actions.negate(42))
print(actions.greet("Praia"))
// ── Sorting with built-in sort ──
let data = [5, 2, 8, 1, 9, 3]
let sorted = data |> sort
print("sorted:", sorted)
sorted.reverse()
print("reversed:", sorted)
print("original unchanged:", data)