Home / Docs / Language guide / Expressions and control flow

take

Release v0.4.0Edition 0.2 and laterU0103U2017U2018U2020U2021

What it does

From edition 0.2, a parameter declared take consumes its argument, which means the caller gives the value away: after f(take a), the caller cannot use a until an assignment gives it a new value. This lets the backend (the part of the compiler that produces the running program) reuse the memory of the value passed instead of copying it. That reuse is never observable, so the meaning stays that of values.

Learn more: Giving a value up: take.

una
module shop

pub kind Cart
  items: Int

pub checkout(take cart: Cart) -> Int = cart.items

pub close(cart: Cart) -> Int
=
  let count = checkout(take cart)
  count

Forms

In the grammar below, each rule gives a name, =, what the name stands for and ;, quoted words are written as shown, NEWLINE, INDENT and DEDENT stand for a line break and for one more or one less level of indentation, [ ] marks an optional part, { } a part that may repeat, | separates alternatives, ( ) groups them, and (* *) holds a comment.

ebnf
param           = [ "edit" | "take" ] lower_ident ":" type ;
arg             = [ lower_ident ":" ] ( "edit" place | "take" lower_ident | line_expr ) ;

Examples

A let edit binding can be given a new value after it was taken, and is usable again:

una
module shop

pub ship(take items: List[Int]) -> Int = items.len

pub ship_and_refill(items: List[Int]) -> Int
=
  let edit stock = items
  let shipped = ship(take stock)
  stock = [1, 2]
  stock.len + shipped

Using a binding after it was taken is rejected:

una
-- fails with U2017
module shop

pub ship(take items: List[Int]) -> Int = items.len

pub ship_twice(items: List[Int]) -> Int
=
  let shipped = ship(take items)
  items.len + shipped

Edge cases

The marker is required:

una
-- fails with U2020
module shop

pub ship(take items: List[Int]) -> Int = items.len

pub ship_unmarked(items: List[Int]) -> Int = ship(items)

A binding, not a field:

una
-- fails with U2020
module shop

pub kind Order
  items: List[Int]

pub ship(take items: List[Int]) -> Int = items.len

pub ship_order(order: Order) -> Int
=
  let shipped = ship(take order.items)
  shipped

Further rules:

Diagnostics

Edition

take exists from edition 0.2 on. In edition 0.1 it is reserved:

una
-- edition 0.1
-- fails with U0103
module shop

pub ship(take items: List[Int]) -> Int = items.len

Normative source