aboutsummaryrefslogtreecommitdiffhomepage
path: root/std/Math.bruijn
blob: 9d3dff25419670ea5c4ab925ed398f029bcdc570 (plain) (blame)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# MIT License, Copyright (c) 2022 Marvin Borner

:import std/List .

:input std/Number .

# adds all values in list
sum foldl add (+0)

∑‣ sum

:test (∑((+1) : ((+2) : ((+3) : empty)))) ((+6))

# returns max value of list
lmax foldl1 max

:test (lmax ((+1) : ((+3) : ((+2) : empty)))) ((+3))

# returns min value of list
lmin foldl1 min

:test (lmin ((+2) : ((+1) : ((+0) : empty)))) ((+0))

# list from num to num
{…→…} z [[[rec]]]
	rec (1 =? ++0) case-end case-list
		case-list 1 : (2 ++1 0)
		case-end empty

:test ({ (+0) → (+2) }) ((+0) : ((+1) : ((+2) : empty)))

# equivalent of mathematical sum function
∑…→…|… z [[[[[rec]]]]] (+0)
	rec (2 =? ++1) case-end case-sum
		case-sum 4 (3 + (0 2)) ++2 1 0
		case-end 3

:test (∑ (+1) → (+3) | ++‣) ((+9))

# multiplies all values in list
product foldl mul (+1)

Π product

:test (Π ((+1) : ((+2) : ((+3) : empty)))) ((+6))

# equivalent of mathematical product function
∏…→…|… z [[[[[rec]]]]] (+1)
	rec (2 =? ++1) case-end case-sum
		case-sum 4 (3 * (0 2)) ++2 1 0
		case-end 3

:test (∏ (+1) → (+3) | ++‣) ((+24))

# greatest common divisor
gcd z [[[(1 =? 0) case-eq ((1 >? 0) case-gre case-les)]]]
	case-eq 1
	case-gre 2 (1 - 0) 0
	case-les 2 1 (0 - 1)

:test ((gcd (+2) (+4)) =? ((+2))) (true)
:test ((gcd (+10) (+5)) =? ((+5))) (true)
:test ((gcd (+3) (+8)) =? ((+1))) (true)

# power function
pow […!!… (iterate (…*… 0) (+1))]

…**… pow

:test (((+2) ** (+3)) =? ((+8))) (true)

# factorial function
# TODO: faster fac?
fac [∏ (+1) → 0 | i]

:test ((fac (+3)) =? (+6)) (true)

# fibonacci sequence
# TODO: faster fib?
fibs fst <$> (iterate [~0 : (^0 + ~0)] ((+0) : (+1)))

fib [fibs !! ++0]

:test (fib (+5)) ((+8))