2023-05-04 05:42:45 +02:00
|
|
|
fn get_number_input(question string) {
|
|
|
|
println(question)
|
2023-05-25 00:22:03 +02:00
|
|
|
input := read_line()
|
2023-05-04 05:42:45 +02:00
|
|
|
// try to parse to an int, then a float.
|
2023-05-25 00:22:03 +02:00
|
|
|
in := match input {
|
2023-05-04 05:42:45 +02:00
|
|
|
input.parse_int() input
|
|
|
|
input.parse_float() input
|
|
|
|
}
|
|
|
|
// 'in' has type int/float/[] because of the match statement
|
|
|
|
switch! in {
|
|
|
|
int/float in
|
|
|
|
// replace [] with an appropriate error before returning
|
|
|
|
[] Err: "input was not a number."
|
|
|
|
}
|
|
|
|
// return type is int/float/Err(string)
|
|
|
|
}
|
|
|
|
|
2023-05-25 00:22:03 +02:00
|
|
|
answer := get_number_input("What is your favorite number?")
|
2023-05-04 05:42:45 +02:00
|
|
|
|
2023-05-18 02:12:21 +02:00
|
|
|
answer.debug() // type: int/float/Err(string)
|
2023-05-04 05:42:45 +02:00
|
|
|
// switch can be used to branch based on a variables type.
|
|
|
|
// switch! indicates that every possible type must be handled.
|
|
|
|
switch! answer {
|
|
|
|
int {
|
|
|
|
println("Entered an integer")
|
2023-05-18 02:12:21 +02:00
|
|
|
answer.debug() // type: int
|
2023-05-04 05:42:45 +02:00
|
|
|
}
|
|
|
|
float {
|
|
|
|
println("Entered a decimal number")
|
2023-05-18 02:12:21 +02:00
|
|
|
answer.debug() // type: float
|
2023-05-04 05:42:45 +02:00
|
|
|
}
|
|
|
|
Err(string) println("Input was not a number!")
|
|
|
|
}
|
|
|
|
|
2023-05-18 02:12:21 +02:00
|
|
|
// wait one second
|
|
|
|
sleep(1)
|
2023-05-04 05:42:45 +02:00
|
|
|
|
|
|
|
|
|
|
|
// function that returns an anonymous function (function object).
|
|
|
|
// anonymous functions can be used as iterators in for-loops.
|
2023-05-18 02:12:21 +02:00
|
|
|
fn square_numbers() {
|
2023-05-25 00:22:03 +02:00
|
|
|
i := 0
|
2023-05-04 05:42:45 +02:00
|
|
|
() {
|
2023-05-25 00:22:03 +02:00
|
|
|
&i = i + 1
|
2023-05-18 02:12:21 +02:00
|
|
|
i * i
|
2023-05-04 05:42:45 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-18 02:12:21 +02:00
|
|
|
for num square_numbers() {
|
2023-05-04 05:42:45 +02:00
|
|
|
println(num.to_string())
|
2023-05-18 02:12:21 +02:00
|
|
|
// once num is greater than 60, the loop stops.
|
|
|
|
num.gt(50)
|
|
|
|
}
|