Types, patterns and values
Slide 34 of 85
34:= elseTypes, patterns and values

Binding with a pattern

Grammar: pattern-decl, arm, position
pattern:=expressionelse{armarm}
pattern-decl = pattern ":=" expression "else" "{" arm { arm } "}" ;
position,positionblock
arm = position { "," position } block ;
_pattern-INTFLOATATOMtruefalse
position = "_" | pattern | [ "-" ] INT | FLOAT | ATOM | "true" | "false" ;

A pattern on the left of := binds what it takes from the value on the right for the rest of the block, and the else after it holds an arm for every value the pattern does not take. The arms are a switch's, with one position each — a pattern, a literal or _ — and the first that matches runs.

Every arm has to leave the block: it ends in return, panic, break or continue, or in an if or a switch whose every branch does, and an arm that could reach its end is a compile error. So nothing after the binding runs without what it bound, and an error is dealt with on the spot, in the arms beside the call that made it — there is no shorter way to the value that puts it off.

It is held to everything a switch is:

  • the value is evaluated once, so a call is as good as a variable;
  • the pattern and the arms together take every value there can be, and the message names one they miss — Result.Ok(Shape.Rectangle(_, _));
  • an arm that can never run, because the pattern or the arms above it already take what it would, is an error too.

What the pattern binds is immutable and belongs to the block it is written in, so a name the block already has is an error, as it is for a plain :=.

Handling the error where it happens
type Order {
	Placed { item: Str, quantity: Int }
	Cancelled
}

func find(orders: Order[], index: Int): Result<Order, Str> {
	if orders bounds index {
		return Result.Ok(orders[index])
	}
	return Result.Error("there is no order {index}")
}

// Past each else the pattern has matched, since every arm leaves first.
func describe(orders: Order[], index: Int): Str {
	Result.Ok(order) := find(orders, index) else {
		Result.Error(why) { return why }
	}
	Order.Placed(item, quantity) := order else {
		Order.Cancelled { return "order {index} was cancelled" }
	}
	return "{quantity} of {item}"
}

proc main(): void {
	orders := [Order.Placed("bees", 3), Order.Cancelled()]
	echo describe(orders, 0)   // 3 of bees
	echo describe(orders, 1)   // order 1 was cancelled
	echo describe(orders, 7)   // there is no order 7
}
Any pattern, and leaving a loop
// A vector pattern, with the empty vector as the one other case.
func total(prices: Int[]): Int {
	[first, ...rest] := prices else {
		[] { return 0 }
	}
	return first + total(rest)
}

proc main(): void {
	echo total([3, 4, 5])   // 12
	for each line in ["move 3", "", "turn left"] {
		// continue leaves the block as surely as return does.
		"{verb} {argument}" := line else {
			_ { continue }
		}
		echo "{verb}: {argument}"
	}
}