// no argsfntest{
10// implicitly returns last line
}
test() ==10// true// return type hint (null negates implicit return)
fn test : Null{
10// is not returned
}
test() // null// unnamed argfnsqare(n){
n*n
}
sqaure(4) // 16// argument defaultfnsquare(n=0){
n*n
}
square() // 0// argument type hint + defaultfnsquare(n : Int=0) : Int{
n*n
}
square(5) // 25// named argfnrecip(:n) : Float{
1/n
}
recip(n: 4) // 0.25// named arg + type hint + defaultfnrecip(n: 1 : Int) : Float{
1/n
}
recip() // 1.0// variadic args (collected as vector)fnsum(*i : Float=[]) : Float{
t=0t+=nforeachn=~it
}
sum(1,3,5) // 9// keyword args (collected as map)fnvowels(**kws){
kws=~ [:a, :e, :i, :o, :u]
}
vowels(a: 1,c: 2,e: 3) // {a: 1, e: 3}// anonymous functionsfn(:x : Int){
x*2
}(x: 3) // 6
Types & structs
// type aliastypeWeightFloat// anonymous structstruct {
x : Int
}
// struct typetypePointstruct {
x, y : Int
}
// static type methodfnPoint#new(x : Int, y : Int){
Point { x, y }
}
// instance method
fn Point::move(x : Int, y : Int){
self->x+=xself->y+=yself
}
try{// something that causes an error}rescue e : TypeError{// catch TypeError exceptions}rescueRangeError{// catch RangeError exceptions}rescue{// catch other exceptions}ensure{// do something after either block (optional)}
Code loading & pragmas
// require files in top-level namespacerequire"file1", "file2"// require file to namespace "name"requirename: "file"// use pragma "pragma"use"pragma"