lang_2023/tests/functions.lang

69 lines
1.4 KiB
Text
Raw Normal View History

2023-06-03 19:01:03 +03:00
decl sum 'a[#add] : 'a -> 'a -> 'a
2023-04-29 13:05:14 +03:00
def sum : a b = a + b
2023-03-31 12:10:12 +03:00
2023-06-03 19:01:03 +03:00
decl fib : \int -> \int
2023-03-31 12:10:12 +03:00
def fib : n =
match n with
| 0 | 1 -> 1
2023-06-03 19:01:03 +03:00
| n ?? n > 1 -> fib: (n - 1) + fib: n
| _ -> error: "n must be positive"
2023-03-31 12:10:12 +03:00
2023-06-03 19:01:03 +03:00
decl fact : \int -> \int
2023-03-31 12:10:12 +03:00
def fact : n =
match n with
| 0 -> 1
2023-06-03 19:01:03 +03:00
| n ?? n > 0 -> n * fact: (n - 1)
| _ -> error: "n must be positive"
2023-03-31 12:10:12 +03:00
2023-06-03 19:01:03 +03:00
decl find-prefix-hashes 'h[#acc-hash[char]] : \string -> \array['h]
def find-prefix-hashes : str = {
var hashes = \array['h]..new: (str..size: + 1)
2023-06-03 19:01:03 +03:00
; hashes`0 = 'h..of: str`0
for i in 1--hashes..size: do {
; hashes`i = hashes`(i - 1)
2023-06-03 19:01:03 +03:00
; hashes`i..append: str`i
}
2023-03-31 12:10:12 +03:00
return hashes
2023-03-31 12:10:12 +03:00
}
2023-06-03 19:01:03 +03:00
alias \hash = \acc-hash[char]
2023-03-31 12:10:12 +03:00
2023-07-03 19:05:50 +03:00
decl find-substring : ::str \string -> ::substr \string -> \array[index]
2023-06-03 19:01:03 +03:00
def find-substring : str substr = {
var result = \array[index]..empty:
2023-03-31 12:10:12 +03:00
2023-07-03 19:05:50 +03:00
let str-hashes = find-prefix-hashes:[hash] str
let substr-hash = \hash..of: substr
2023-03-31 12:10:12 +03:00
2023-06-03 19:01:03 +03:00
for i in 0--(str-hashes..size: - substr..size:) do {
2023-07-03 19:05:50 +03:00
let part-hash = hash..diff: str-hashes`(i + substr..size:) str-hashes`i
2023-03-31 12:10:12 +03:00
2023-06-03 19:01:03 +03:00
if part-hash == substr-hash then {
; result..push: i
2023-03-31 12:10:12 +03:00
}
}
return result
}
2023-06-03 19:01:03 +03:00
decl is-empty : -> \bool
def is-empty = 0
2023-03-31 12:10:12 +03:00
2023-06-03 19:01:03 +03:00
decl do-something : -> \unit
def do-something =
\io..print: "Hello World!"
2023-03-31 12:10:12 +03:00
2023-06-03 19:01:03 +03:00
decl mul : \int -> \int -> \int
2023-03-31 12:10:12 +03:00
def mul : x y = x * y
2023-06-03 19:01:03 +03:00
decl mul-10 : \int -> \int
def mul-10 = mul: 10
2023-07-03 19:05:50 +03:00
exec main {
; find-substring:
::str "abacaba"
::substr "bac"
}