Skip to content
More than one result

More than one result

A function returns one value. When it has two things to say, declare a record for the pair and return that.

record halves { before: bytes, after: bytes }

fn split_at_first(text: bytes, separator: int) -> halves {
  let at = index_of_byte(text, separator, 0);
  if at == len(text) { halves(before: text, after: "") }
  else { halves(before: slice(text, 0, at), after: slice(text, at + 1, len(text))) }
}

fn equals_sign() -> int { 61 }

fn main() -> int {
  let parts = split_at_first("mira=17", equals_sign());
  print(concat4(parts.before, " and ", parts.after, "\n"))
}
bootstrap/qdx run std/*.qdx split.qdx
mira and 17

A result and what is left

The same shape serves any function that consumes part of its input: return what it made, together with the rest. The qdx compiler’s own parser is written this way. Every parsing function takes the remaining tokens and returns a record of the thing it read and the tokens after it.

Carrying something through a walk

When a walk over a list needs to keep two running values, there are two options. Give the function two carried parameters, which is simplest when the values are independent. Or carry one record that holds both, which is better when they travel together through several functions.

Names for bytes

A byte is a number, and qdx has no character literal. Give each one you use a small function with a name, as equals_sign does, so the number appears once.