Skip to content
FutureBlitz

    Install

    The tour, 4 of 11

    Functions

    Parameters, defaults and named arguments, tuples, lambdas, and closures.

    A Function’s parameters and result have their types written. One without a result type gives nothing, and one that’s a single expression can be written after =>.

    Import std.core
    
    Function Add(a: Int, b: Int): Int
        Return a + b
    End Function
    
    Function Square(x: Float): Float => x * x
    
    Function Greet(name: String)
        Print("Hello, {name}")
    End Function
    
    Print(Add(2, 3), Square(1.5))
    Greet("Ada")
    Output
    5 2.25
    Hello, Ada

    Functions are seen anywhere in their file, above or below the code that calls them.

    Defaults and named arguments

    Import std.core
    
    Function Spawn(name: String, hp: Int = 100, boss: Bool = False): String
        Return "{name} ({hp} hp{boss ? ", boss" : ""})"
    End Function
    
    Print(Spawn("grunt"))
    Print(Spawn("ogre", 400))
    Print(Spawn("king", boss: True))
    Output
    grunt (100 hp)
    ogre (400 hp)
    king (100 hp, boss)

    Tuples

    A Function gives several values as a tuple, which a Local takes apart.

    Import std.core
    
    Function MinMax(values: Int[]): (Int, Int)
        Local low = values[0]
        Local high = values[0]
        For v In values
            If v < low Then low = v
            If v > high Then high = v
        End For
        Return (low, high)
    End Function
    
    Local low, high = MinMax([4, 9, 1, 7])
    Print("from {low} to {high}")
    Output
    from 1 to 9

    Lambdas and closures

    A Function is a value too, of a type like Func(Int): Int. A lambda can use the variables around it, and keeps them as long as it lives.

    Import std.core
    
    Function MakeCounter(): Func(): Int
        Local count = 0
        Return Function()
            count += 1
            Return count
        End Function
    End Function
    
    Local twice = Function(x: Int) => x * 2
    Print(twice(21))
    
    Local next = MakeCounter()
    next()
    next()
    Print(next())
    Output
    42
    3

    A ByRef parameter changes the caller’s variable, and the call says so too: Swap(ByRef a, ByRef b). Next: arrays and Maps.

    Next: Arrays and Maps

    Report an issue with this page or with FutureBlitz on GitHub.