Skip to content
Values and functions

Values and functions

In Mira’s game a player rolls two dice and scores their sum. Rolling a double scores twice as much. Put this in round.qdx.

fn round_score(first_die: int, second_die: int) -> int {
  let sum = first_die + second_die;
  if first_die == second_die { sum * 2 } else { sum }
}

fn main() -> int {
  print(concat3("Mira scores ", int_to_text(round_score(6, 6)), "\n"))
}
bootstrap/qdx run std/*.qdx round.qdx
Mira scores 24

Three kinds of value

  • int is a whole number of 64 bits, written in decimal. The operators are +, -, *, / and %. Division drops the fraction, so 7 / 2 is 3.
  • bool is true or false. Comparisons such as ==, !=, < and >= produce one, and and, or and not combine them.
  • bytes is a run of bytes, usually text. "Mira scores " is a bytes literal.

There are no automatic conversions between them. A number is turned into text by int_to_text, and text is joined by concat, or by concat3 when there are three pieces.

Functions

A function names its parameters and their types, then its result type after ->. Its body is a block, and the block’s last line is the result. There is no return keyword.

let

let gives a name to a value for the rest of the block. A line that starts with let ends with a semicolon. The last line of a block has no semicolon, because it is the block’s value.

The name cannot be given a new value later. You can, however, use the same name in a later let, which hides the earlier one from that point on.

if

if chooses between two blocks and produces the value of the one it runs. Both must produce the same type, and the else is required. A chain is written else if.

round_score knows the rule for one round. A game has many rounds, and the next chapter adds them up.