11. Defining reusable vocabulary
Reusable behavior is defined directly in Stated source. A file can contain multiple named functions, and one function can call another with named arguments.
Complete named functions
This source defines quadruple in terms of double-value:
txt
Define quadruple as a function.
It accepts an integer named input.
Call double-value with the input as input, storing the result as doubled.
Call double-value with the doubled as input, storing the result as quadrupled.
Return the quadrupled.
Define double-value as a function.
It accepts an integer named input.
Return the doubled value of the input.The corresponding callable Go is generated directly from those definitions:
go
package generated
import (
"errors"
"math"
)
func Quadruple(p0 int64) (int64, error) {
r0, err0 := DoubleValue(p0)
if err0 != nil {
return 0, err0
}
_ = r0
r1, err1 := DoubleValue(r0)
if err1 != nil {
return 0, err1
}
_ = r1
return r1, nil
}
func DoubleValue(p0 int64) (int64, error) {
v1 := p0
_ = v1
if (v1 > 0 && v1 > math.MaxInt64-v1) || (v1 < 0 && v1 < math.MinInt64-v1) {
return 0, errors.New("integer overflow")
}
v2 := v1 + v1
return v2, nil
}Calls may target a function defined later in the same file. The compiler resolves all definitions before emitting Go and rejects duplicate names, unknown callees, incorrect arguments, and recursive call cycles.
Exercise
Which source sentence supplies the Go name DoubleValue?
Verified solution
Define double-value as a function. supplies the name. Stated converts the hyphenated source name to an exported Go identifier.