English | Japanese SourceForge.JP
Copyright (c) 2011-2012 Yutaka Saito

Block Expression

You can declare functions that has a block expression. This mechanism is used in variety of ways such as implementation of statements like if and while, initial declaration of list and dictionary items, and so on.

The following is a simple example of declaring a function with a block.

f(x:number) {block} = {
    block(x)
    block(x + 1)
    block(x + 2)
}

You can call it like follows.

f(2) {|x|
    print(x)
} # 234

A block itself is a function object that has a special variable scope. and it takes a list of block parameter as its arguments. You can use any argument specifier like optional argument, default values and variable-length arguments for block parameters as well.

x = 0
f(2) {|x|
    print(x)
}
println(x)        # 0

You can use any symbol to specify the block.

f(x:number) {yield} = {
    yield(x)
    yield(x + 1)
    yield(x + 2)
}

A block specified by a symbol with a question character suffix shall be treated as an optional one. If the function is called without a block, that symbol is assigned to nil.

f_opt() {block?} = {
    if (block == nil) {
        println('not specified')
    } else {
        block()
    }
}

f_opt() # print 'not specified'

f_opt() {
    println('message from block')
}       # print 'message from block'

A block usually works with a variable scope that can access to an 'external' environment of the function.

g() {block} = {
    block()
}

n = 2
g() {
    n = 5
}
printf('n = %d\n', n) # n = 5