aboutsummaryrefslogtreecommitdiffhomepage
path: root/std/Number/Conversion.bruijn
blob: 005731055a17a1a8e0f0126c948ff4d417445db1 (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
# MIT License, Copyright (c) 2024 Marvin Borner
# convert bases to other bases

:import std/Combinator .
:import std/Number/Unary U
:import std/Number/Binary B
:import std/Number/Ternary T

# converts unary numbers to ternary
unary→ternary [0 T.inc (+0t)] ⧗ Unary → Ternary

:test (unary→ternary (+0u)) ((+0t))
:test (unary→ternary (+2u)) ((+2t))

# converts ternary numbers to unary
ternary→unary [T.apply 0 U.inc (+0u)] ⧗ Ternary → Unary

:test (ternary→unary (+0t)) ((+0u))
:test (ternary→unary (+2t)) ((+2u))

# converts binary numbers to ternary
# constructs reversed path of composed functions and applies to ternary
binary→ternary [y [[[rec]]] [0] 0 (+0t)] ⧗ Binary → Ternary
	rec B.zero? 0 case-end case-rec
		case-rec B.odd? 0 (2 (1 ∘ T.inc) (B.dec 0)) (2 (1 ∘ (T.mul (+2t))) (B.div² 0))
		case-end 1

:test (T.eq? (binary→ternary (+0b)) (+0t)) ([[1]])
:test (T.eq? (binary→ternary (+42b)) (+42t)) ([[1]])

# converts numbers to binary
# constructs reversed path of composed functions and applies to ternary
ternary→binary [y [[[rec]]] [0] 0 (+0b)] ⧗ Ternary → Binary
	rec T.zero? 0 case-end case-rec
		case-rec T.odd? 0 (2 (1 ∘ B.inc) (T.dec 0)) (2 (1 ∘ (B.mul (+2b))) (T.div² 0))
		case-end 1

:test (B.eq? (ternary→binary (+0t)) (+0b)) ([[1]])
:test (B.eq? (ternary→binary (+42t)) (+42b)) ([[1]])