lang_2023/tests/functions.lang

63 lines
1.3 KiB
Text
Raw Permalink Normal View History

2023-03-31 12:10:12 +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
decl fib : Int -> Int
def fib : n =
match n with
| 0 | 1 -> 1
| n ? n > 1 -> fib: (n - 1) + fib: n
| _ -> error: "n must be positive"
2023-03-31 12:10:12 +03:00
decl fact : Int -> Int
def fact : n =
match n with
| 0 -> 1
| n ? n > 0 -> n * fact: (n - 1)
| _ -> error: "n must be positive"
2023-03-31 12:10:12 +03:00
2023-04-25 21:21:36 +03:00
decl find_prefix_hashes ('H : (#AccHash Char)) : String -> (Array 'H)
def find_prefix_hashes : str = {
var hashes = (Array 'H).new: (str.size: + 1)
; hashes`0 = 'H.of: str`0
2023-05-11 23:14:36 +03:00
for i in 1--hashes.size: do {
; hashes`i = hashes`(i - 1)
; hashes`i.append: str`i
}
2023-03-31 12:10:12 +03:00
return hashes
2023-03-31 12:10:12 +03:00
}
2023-04-25 21:21:36 +03:00
alias Hash = (AccHash Char)
2023-03-31 12:10:12 +03:00
2023-04-25 21:21:36 +03:00
decl find_substring : String -> String -> (Array Index)
2023-03-31 12:10:12 +03:00
def find_substring : str substr = {
var result = (Array Index).empty:
2023-03-31 12:10:12 +03:00
const str_hashes = find_prefix_hashes Hash: str
const substr_hash = Hash.of: substr
2023-03-31 12:10:12 +03:00
2023-05-11 23:14:36 +03:00
for i in 0--(str_hashes.size: - substr.size:) do {
const part_hash = Hash.diff: str_hashes`(i + substr.size:) str_hashes`i
2023-03-31 12:10:12 +03:00
if part_hash == substr_hash then {
; result.push: i
2023-03-31 12:10:12 +03:00
}
}
return result
}
2023-05-13 14:54:48 +03:00
decl is_empty : -> Bool
2023-04-25 21:21:36 +03:00
def is_empty = 0
2023-03-31 12:10:12 +03:00
2023-05-13 14:54:48 +03:00
decl do_something : -> Unit
2023-03-31 12:10:12 +03:00
def do_something =
IO.print: "Hello World!"
2023-03-31 12:10:12 +03:00
decl mul : Int -> Int -> Int
def mul : x y = x * y
decl mul_10 : Int -> Int
def mul_10 = mul: 10