module use "std/vecopt.nib"
Vec.Opt
The Vec reads that can miss — get, first, last, find_index — answering an Option instead of raising or answering -1.
Vec.get, Vec.first and Vec.last raise Err.IndexOutOfRange when there is no element to answer, and Vec.find_index answers -1 when nothing matches. That is right when a miss is a bug. When a miss is an ordinary outcome, the functions in Vec.Opt ask the same questions and answer an Option: Option.Some(x) when there is an answer, Option.None when there is not. None of them raises.
Vec.Opt.get and Vec.get sit side by side; which one a call means is visible in the call. Add use "std/vecopt.nib" to reach them, and use "std/option.nib" as well to match on the answer — a file can name the Some and None arms only when it uses the file that declares them.
let names = #["ada", "bo", "cy"];
match Vec.Opt.get(names, 5)
Some(n) => "found {n}"
None => "only {Vec.size(names)} names"
end
only 3 names
Functions
func get :: v: Vec<'t>, i: Int -> Option.Option<'t>
The element at index i as Some(x), or None when i is negative or not less than Vec.size.
(Vec.Opt.get(#[10, 20, 30], 1), Vec.Opt.get(#[10, 20, 30], 3), Vec.Opt.get(#[10, 20, 30], -1))
(Option.Some(20), Option.None, Option.None)
func first :: v: Vec<'t> -> Option.Option<'t>
The first element as Some(x), or None for an empty Vec.
let empty: Vec<String> = #[];
(Vec.Opt.first(#["head", "tail"]), Vec.Opt.first(empty))
(Option.Some("head"), Option.None)
func last :: v: Vec<'t> -> Option.Option<'t>
The last element as Some(x), or None for an empty Vec.
let empty: Vec<String> = #[];
(Vec.Opt.last(#["head", "tail"]), Vec.Opt.last(empty))
(Option.Some("tail"), Option.None)
func find_index :: v: Vec<'t>, p: ('t) -> Bool -> Option.Option<Int>
The index of the first element for which p answers true, as Some(i), or None if no element matches. Unlike Vec.find_index, a miss cannot be mistaken for an index.
let v = #["a", "b", "c"];
(Vec.Opt.find_index(v, { s -> s == "a" }), Vec.Opt.find_index(v, { s -> s == "z" }))
(Option.Some(0), Option.None)