λleanlab

Handling missing values

Option makes missing values explicit, so the compiler helps you handle both outcomes.

Open Options.lean in editor
def describe (input : String) : String :=
  match input.toNat? with
  | some n => s!"You entered {n}"
  | none => "That is not a natural number"

def main : IO Unit := do
  IO.println (describe "42")
  IO.println (describe "hello")

Explanation

Option Nat

Either some n containing a number, or none representing a missing value.

toNat?

Attempts to parse a natural number from a string. The question mark is part of the name.

some / none

The two constructors of Option. Pattern matching forces us to consider both.

Expected output

Reference only. Run the file to check its actual result.

You entered 42
That is not a natural number

Exercise

Try "-4" and "007" as inputs.