DocsLanguage Guide
Functions
Labels, defaults, variadics, inout and out parameters, overloading, generators and function types.
A function is a named piece of code that does one job. You give it a name that says what the job is, and call it by that name, passing it the values it needs.
Sable's functions combine C#'s and Swift's. As in Swift, a parameter can have an external label that reads well at the call site, a default value, or be variadic, and functions are values with types of their own. As in C#, a parameter with a single name may be called with or without that name, and out parameters exist alongside inout ones. A function can also be a generator, producing a sequence one element at a time with yield.
Defining and Calling Functions#
A function is declared with fn, its name, its parameters in parentheses, and after -> the type of value it returns:
fn greeting(for person: String) -> String { return "Hello, " + person + "!"}print(greeting(for: "Ada")) // Hello, Ada!A function that returns nothing leaves out the arrow. Its result type is Void, which is also written ():
fn logLine(_ message: String) { print("[log] \(message)")}When the body is a single expression, write it after => instead of in braces. The value of the expression is what the function returns:
fn square(_ x: Int) -> Int => x * xfn isEven(_ n: Int) -> Bool => n % 2 == 0Functions are declared at the top level of a module, as members of types, or inside other functions.
Return Values#
A function returns one value of its declared type. To return several, return a tuple, and give its elements labels so the caller can read them by name:
fn divmod(_ a: Int, _ b: Int) -> (q: Int, r: Int) { return (q: a / b, r: a % b)}let result = divmod(17, 5)print("\(result.q) remainder \(result.r)") // 3 remainder 2let (q, r) = divmod(9, 4) // or take it apartTo say that there may be no value, return an optional (see Optionals); to say that the call may fail, make the function throw (see Error Handling).
A function whose result type is Never never returns at all: it traps, exits the process, or loops forever. The compiler knows that code after a call to one is unreachable.
Ignoring a Result#
Calling a function for its effects and dropping the value it returns is often a mistake (text.trimmed() on its own line changes nothing), so a call whose result is unused is a warning (S3308). Write _ = in front to drop a value on purpose:
_ = stock.remove("lamp") // the old value, not wanted hereA function for which calling it just for its effects is normal can say so with @discardable, and then no warning is given:
@discardablefn record(_ name: String, in seen: inout [String: Bool]) -> Bool { let isNew = seen[name] == none seen[name] = true return isNew // whether it was new: useful, but optional}Parameter Labels#
Each parameter has a name, used inside the function. It may also have an external label, written before the name, which the caller uses:
fn relocate(from source: Point, to destination: Point) { // 'source' and 'destination' inside}relocate(from: home, to: office)Labels let a call read like a sentence while the body uses names that suit it. A label can be any word, a keyword included, so fn first(where predicate: …) and parse(tokens, in: arena) are fine.
Write _ as the label when the call reads better without one:
fn insert(_ item: String, at index: Int) { }insert("lamp", at: 3)Optional Labels#
When a parameter has a single name, that name is its label, and the label is optional at the call site. This is C#'s rule, and differs from Swift, where the label would be required:
fn resize(width: Int, height: Int) { }resize(800, 600) // legalresize(width: 800, height: 600) // also legal, and clearerA parameter with an external label (from source) needs that label, and one declared _ takes none. Where two overloads differ only in their labels, fn scaled(by: Int) and fn scaled(to: Int), the label is needed to say which one you mean.
Default Parameter Values#
A parameter can have a default value, written after its type. A call may leave that argument out:
fn connect(host: String, port: Int = 443, timeout: Duration = .seconds(30)) { }connect(host: "example.org")connect(host: "example.org", port: 8443)Put parameters with defaults after those without, so that calls look alike with and without them.
A default is worked out at each call that leaves it off, not once when the function is declared, so a default such as Date.now() or [] is fresh every time. It is worked out in the place it is written, though: the names it uses mean what they mean at the declaration, not at the call. A generic function's default takes the types that call gives its type parameters:
fn count<E>(_ queue: Queue<E> = Queue<E>()) -> Int { }A call of count that leaves the argument off, and whose E is F64, makes a fresh Queue<F64>. Generics are covered in Generics.
Variadic Parameters#
A variadic parameter takes any number of arguments, including none, written with ... after its type. Inside the function it is an array of them:
fn total(_ values: Int...) -> Int { var sum = 0 for value in values { sum += value } return sum}print(total(1, 2, 3)) // 6print(total()) // 0Parameters That Change the Caller's Values#
Parameters are constants: a function cannot assign to one. Arguments are passed as values, so a function working on its own copy cannot change the caller's variable either. When a function should change a value the caller owns, the parameter says so.
In-Out Parameters#
An inout parameter is given exclusive access to the caller's variable for the length of the call. Whatever the function writes to it, the caller's variable holds afterwards. At the call, the argument is written with & in front, to show that the call may change it:
fn scale(_ v: inout Vec3, by factor: F32) { v.x *= factor v.y *= factor v.z *= factor}var velocity = Vec3(x: 1, y: 2, z: 3)scale(&velocity, by: 2)print(velocity.y) // 4.0& is required for an inout or out argument and is an error anywhere else (S3209), so every call that can change your variables is marked where you read it. The argument must be a place an assignment could write: a var, a field or element of one, a property or subscript with a setter. An element of a let array, or of an array a call returns, is not one: &make()[0] is refused (S3010) rather than writing to a copy that is then thrown away.
While the call is running, nothing else may touch the variable passed inout, so passing the same variable twice, swapValues(&a, &a), is an error (S3062). This is the law of exclusivity, which Memory and Ownership explains.
A range of an array can be passed inout too, sortAll(&scores[1..<4]), as described in Arrays and Collections.
Out Parameters#
An out parameter is one the function must assign before it returns, and may not read before it does. It is how a function gives back a second result, in the style of C#'s TryParse:
fn tryParse(_ text: String, out value: Int) -> Bool { if let n = text.toInt() { value = n return true } value = 0 return false}var port: Intif tryParse("8080", &port) { print(port) // 8080}The caller's variable need not have a value before the call. The argument may be written out port instead of &port.
Where to Write the Modifier#
An ownership modifier such as inout can go before the parameter name or after the colon. Once a parameter has an external label, put it after the colon, since fn read(into buffer: inout U8[>..]) reads better than fn read(inout into buffer: U8[>..]).
Consuming Parameters#
A consuming parameter takes ownership of its argument: the caller's binding is finished with once it is passed. This matters for move-only types such as file handles, where only one owner may exist:
@noncopystruct Ticket { let seat: String}fn redeem(consuming ticket: Ticket) { print("seat \(ticket.seat)")}let ticket = Ticket(seat: "14C")redeem(ticket)// using 'ticket' here is an error: it was given awayAt the call site, move hands over a copyable value explicitly, ending the caller's binding without a copy or an extra reference count: pool.giveBack(move bytes). After that line, using bytes is an error.
Reference Parameters#
A parameter of type T& reads the caller's value in place for the call, rather than taking a copy. It is mostly worth writing on large structs, and on functions that return a reference into an argument; class instances and move-only values are passed by reference already. It takes a plain argument, with no &, since it only reads:
fn area(_ r: Rect&) -> F64 => r.width * r.heightprint(area(bounds))Whether a function may return a reference rooted in such a parameter is worked out by the compiler from the body and the result type, so you never write a lifetime. That, and & used to make a reference value, are the subject of Memory and Ownership. The words ref and borrowing are not Sable; the compiler reserves them so that it can say so (S1013).
Lazily Evaluated Parameters#
Normally every argument is worked out before the call. An @autoclosure parameter is different: the caller writes a plain expression, and it becomes the body of a closure that the function calls when, and only if, it wants the value.
fn logIfVerbose(_ message: @autoclosure () -> String) { if verbose { print(message()) }}logIfVerbose("state: \(expensiveDump())") // expensiveDump runs only when verboseThe standard library's assert works this way, so a release build, where assert does nothing, works out neither its condition nor its message:
assert(index < count(), "index \(index) is past the end")The rules:
- The attribute is written on the parameter's type, where
@escapinggoes:_ c: @autoclosure () -> Bool. Written before the parameter, it is S1014. - The type must be a
() -> Ttaking nothing, and the parameter cannot beasync, variadic,inout,outorconsuming(S3515). - The expression is worked out each time the function calls the closure, and not at all if it never does.
- A default value is wrapped like an argument, so
_ message: @autoclosure () -> String = ""is fine. - If the expression can throw, the type says so,
() throws -> T, and the caller writestryinside the argument. - The closure does not escape the call unless the parameter is
@escapingtoo. - Passing it on to another
@autoclosureparameter is written as a call,assert(c()), which makes a new closure that calls it only when asked. Writingassert(c)is S3516.
The attribute belongs to the parameter, not to the function type: assert passed as a value is a function that takes a () -> Bool, and its caller writes the closure. An optimised build inlines all of this away, leaving the expression where it is asked for and nothing allocated.
Local and Nested Functions#
A function can be declared inside another. It is visible only inside the function that holds it:
fn report(_ orders: Order[:]) -> String { fn line(_ o: Order) -> String => "\(o.id:>6) \(o.total:>10.2)" var text = "" for o in orders { text += line(o) + "\n" } return text}A nested function that uses nothing from its surroundings is a plain function. One that uses a local of the outer function captures it, and is a closure; capturing is explained in Closures.
Overloading#
Several functions can share a name if their parameters differ in type, number or labels:
fn describe(_ n: Int) -> String => "the number \(n)"fn describe(_ s: String) -> String => "the text \(s)"fn describe(_ p: Point) -> String => "the point (\(p.x), \(p.y))"Two functions cannot differ only in their result type. When a call fits several overloads, Sable prefers, in order: an exact match of the argument types, then a match of the labels, then one that needs an implicit widening, then one reached through a protocol conformance, and last a generic one. A label left out of a call is a worse match than no label at all: with both find(_ x: Int) and find(x: Int), find(3) calls the first. If no rule decides between two, the call is ambiguous (S3008).
Two overloads that differ only in whether a closure they take is async are told apart by the closure: one that awaits goes to the async overload, await measure { await work() }, and any other to the one that is not. (See Concurrency.)
Function Types#
Every function has a type, made of its parameter types and its result type. The type of square above is (Int) -> Int; a function taking two strings and returning nothing is (String, String) -> (). You use function types like any other type:
fn add(_ a: Int, _ b: Int) -> Int => a + bfn multiply(_ a: Int, _ b: Int) -> Int => a * bvar operation: (Int, Int) -> Int = addprint(operation(3, 4)) // 7operation = multiplyprint(operation(3, 4)) // 12A function type records the effects too:
| Type | Meaning |
|---|---|
(A) -> B |
takes an A, returns a B |
(A) throws(E) -> B |
may throw an E |
(A) throws -> B |
may throw any error: throws(any Error) |
async (A) -> B |
must be awaited |
(inout A) -> () |
changes the caller's A in place |
(@escaping () -> T) -> () |
may keep the closure it is given beyond the call |
@escaping, and why it is part of the type, is covered in Closures. A type alias gives a long function type a name: alias Handler = async (Request) throws(HttpError) -> Response.
Functions as Parameters and Results#
Because functions are values, they can be passed to other functions and returned from them:
fn applyTwice(_ value: Int, _ transform: (Int) -> Int) -> Int { return transform(transform(value))}print(applyTwice(3, square)) // 81fn stepper(backward: Bool) -> (Int) -> Int { fn forward(_ n: Int) -> Int => n + 1 fn back(_ n: Int) -> Int => n - 1 return backward ? back : forward}let next = stepper(backward: true)print(next(10)) // 9Most of the time the function you pass is written in place as a closure, applyTwice(3) { $0 + 1 }, which is the next chapter's subject.
Generators#
A function whose result type is some Sequence<T> or some Iterator<T>, and whose body contains yield, is a generator. Each yield gives the next element; return with no value, or reaching the end of the body, ends the sequence.
fn evens(upTo n: Int) -> some Sequence<Int> { var i = 0 while i <= n { yield i i += 2 }}for x in evens(upTo: 6) { print(x) // 0, 2, 4, 6}Methods, computed properties and closures can be generators too:
struct Grid { let width: Int let height: Int fn cells() -> some Sequence<(Int, Int)> { for y in 0..<height { for x in 0..<width { yield (x, y) } } }}A generator is lazy. Calling it runs none of its body; it only captures its arguments, and self for a method, by value. The body runs a step at a time as each element is asked for, and each new iteration over the sequence starts it again from the top. For the same reason a generator cannot have inout or out parameters (S3483): the call has returned before the body runs.
The compiler turns a generator into a sequence struct and an iterator struct, which hold the arguments, the body's variables and the point where it stopped. Going through one allocates nothing, and copying an iterator gives one that carries on from the same point on its own.
Throwing Generators#
A generator declared throws(E) gives a sequence whose Failure is E: an error its body throws comes out of the iterator's next(), so you go through it with for try. Calling it throws nothing, since calling only captures. Once it has thrown, it is finished.
fn records(_ text: String) throws(ParseError) -> some Sequence<Record> { for line in text.lines() { yield try Record.parse(line) }}for try record in records(csv) { print(record.name)}Generators and defer#
A defer in a generator runs when its scope is left, which may be when the generator finishes, or when its iterator is dropped before it finishes, like C#'s finally running on Dispose. So a generator that opens a file can close it whether or not the loop reads to the end. A defer body cannot yield (S3481). A generator with a defer keeps its state in one shared object, so that the last copy of its iterator to go runs the pending defers.
Async Generators#
An async generator returns some AsyncSequence<T> (or some AsyncIterator<T>). Its body may await, and you go through it with for await:
async fn lines(_ f: File) -> some AsyncSequence<String> { while let line = await f.readLine() { yield line }}yield anywhere but a generator's body is an error (S3480), as is a result type that names no sequence of what is yielded, and a return with a value inside a generator (S3482).
The Entry Point#
A program starts at the function marked @main. It must be a function of the module, not a method or a nested function; take no parameters; not be generic; and return either nothing or an Int, which becomes the process's exit status. A module has at most one (S3514).
module Inventory@mainfn main() -> Int { let ok = runChecks() return ok ? 0 : 1}The program's command-line arguments are not parameters of main; read them with Environment.arguments() from Sable.IO. @main can also be on an async fn, so that the program can await from its first line (see Concurrency).