Optional values in Mojo
Optional models a result that may not be there at all.
def first_even(values: List[Int]) -> Optional[Int]:
for value in values:
if value % 2 == 0:
return value
return None
def main():
var found = first_even([3, 5, 8, 9])
if found:
print("first even:", found.value())
var missing = first_even([1, 3, 5])
print("found anything:", Bool(missing))
How it works
first_evenreturns anInton success andNoneotherwise.- An
Optionalis truthy when it holds something, soif found:works. value()unwraps it once that check has passed.
Keywords and builtins used here
IntListdeffirst_evenforifmainprintreturnvar
The run, in numbers
- Lines
- 12
- Characters to type
- 288
- Tokens
- 81
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 61 seconds.
Step 6 of 6 in Collections, step 17 of 26 in Language basics.