The option type is a predefined variant type that is used to express whether there is a value of some type or none. This is especially useful when calling a partial function, that is, a function that is not defined for some inputs. In that case, the value of the option type would be None, otherwise Some (v), where v is some meaningful value of any type.
An example in arithmetic is the division operation:
let div = ([a, b]: [nat, nat]): option<nat> => { if(b == (0 as nat)){ return (None() as option <nat>); } else { return (Some(a/b)); }; };
Option in Pattern matching
In the previous chapters, you’ve seen how to do pattern matching using the match operator. The keyword Some can be used in a pattern matching to retrieve the value behind the option variable. The keyword None can be used in a pattern matching to verify the option variable has no value.
match(<variable>, { Some: (<value_name>) => <block_code>, None: => <block_code> });
<block_code> can be a single instruction or a {} <value_name> is a local variable name. <value_name> which holds the option value and can be used inside the <block_code>
Here is an example of Map.findopt_ operator returning an option type :
type expected_type = int; type balance_type = map<nat, expected_type>; const user_balances: balance_type = Map.literal(list([[1 as nat, 10]])); const my_balance: option<expected_type> = Map.find_opt(1 as nat, user_balances); match(my_balance, { Some: val => unit, None: () => failwith("Unknown user") });
Here is an example of pattern matching resolving an option type directly (useful when we just want to retrieve the value behind the optional) :
const my_balance2: expected_type = match(my_balance, { Some: val => val, None: () => failwith("Unknown user") as expected_type });
Notice the cast of failwith instruction into an expected_type
Your mission
1- Notice the weapons mapping which maps the name of each weapon to its corresponding input of power. We want to increase the power of the Main Laser but mapping returns optional results as they might not be found in the mapping. Define the constant main_laser_power as an optional int from selecting “Main Laser” from the weapons mapping.
2- Writte a pattern matching for main_laser_power. If it exists, increase the power of the “Main Laser” by 1 (use i as temporary matching variable). If it does not exist in the mapping, fail with “Weapon not found”