Options in filter and map

Published .. 26-06-2024
Type ....... article
Tags ....... v

In V the array.map and array.filter does take Result (return possible error) or Option (returns possible none) types.

// Return Option
fn up(x string) ?string {
    if x=="b" {
        return none
    }
    return x.to_upper()
}

// return Result
fn up2(x string) !string {
    if x=="b" {
        return error("no b")
    }
    return x.to_upper()
}

fn main() {
    a:=["a","b","c"]

    // you have to unwrap
    c := a.map(fn (i string) string { return up(i) or { "?" }})
    dump(c)
    
    // can be written using magic it variable
    d := a.map(up(it) or { "?" })
    dump(d)

    e := a.map(up2(it) or { err.str() })
    dump(e)
}