interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / si / rosetta / tasks / binary-search / binary-search.om

98 lines · 1648 bytes Raw Blame History
1note Rosetta Code task "Binary search": https://rosettacode.org/wiki/Binary_search
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text minus "-"
6text found " found at index "
7text nf " not found"
8note emit writes every byte of a to stdout; a short write is retried, an error exits 1
9fn emit a view uchar * to void
10o = ulong 0
11while lt o len a bound 4096
12k = write 1 a o sub len a o
13if le k 0
14exit 1
15end
16o = add o ulong k
17end
18end
19note emitu writes n in decimal; 20 digits hold every ulong
20fn emitu n ulong to void
21d = new uchar 20 0
22i = ulong 20
23v = n
24while true bound 20
25i = sub i 1
26put d i uchar add rem v 10 48
27v = div v 10
28if eq v 0
29break
30end
31end
32emit part d i sub 20 i
33end
34note emiti writes a signed n; the magnitude is taken as a ulong so the minimum long cannot overflow
35fn emiti n long to void
36if lt n 0
37emit minus
38emitu add bitcast ulong not n 1
39else
40emitu ulong n
41end
42end
43note returns the index of x in the sorted a, or -1; 16 elements need at most 5 halvings
44fn bsearch a view long 16 x long to long
45lo = ulong 0
46hi = ulong 16
47while lt lo hi bound 16
48mid = add lo shr sub hi lo 1
49v = get a mid
50if eq v x
51ret long mid
52end
53if lt v x
54lo = add mid 1
55else
56hi = mid
57end
58end
59ret -1
60end
61fn query a view long 16 x long to void
62r = bsearch a x
63emiti x
64if ge r 0
65emit found
66emiti r
67else
68emit nf
69end
70emit nl
71end
72fn main to int
73a = new long 16 0
74put a 0 -40
75put a 1 -12
76put a 2 -3
77put a 3 0
78put a 4 2
79put a 5 5
80put a 6 8
81put a 7 13
82put a 8 21
83put a 9 34
84put a 10 55
85put a 11 89
86put a 12 144
87put a 13 233
88put a 14 377
89put a 15 610
90query a -40
91query a 0
92query a 21
93query a 610
94query a 7
95query a 1000
96query a -41
97ret 0
98end