Monads/Maybe monad: Difference between revisions

Line 503:
=={{header|F_Sharp|F#}}==
<lang fsharp>
// We can use Some as return, Option.bind and the pipeline operator in order to have a very concise code
// Options. Nigel Galloway: February 26th., 2020
 
let fN n g = Seq.tryFind n g //(('a -> bool) -> seq<'a> -> 'a option)
 
printfn "fN returned %A" (fN (fun n->if n="a" then true else false) ["n";"i";"g";"e";"l"])
let f1 (v:int) = Some v // int -> Option<int>
printfn "fN returned %A" (fN (fun n->if n="g" then true else false) ["n";"i";"g";"e";"l"])
let f2 (v:int) = Some(string v) // int -> Option<sting>
match fN (fun n->if n=0 then true else false) [1;2;3;4;5] with
 
Some n->printfn "fN returned %A" n
f1 4 |None> Option.bind -f2 |> printfn "Value notis found%A" // bind when option (maybe) has data
None |> Option.bind f2 |> printfn "Value is %A" // bind when option (maybe) does not have data
match fN (fun n->if n=3 then true else false) [1;2;3;4;5] with
Some n->printfn "fN returned %A" n
|None ->printfn "Value not found"
let fG n=let a=["n";"i";"g";"e";"l"] in if n>=0 && n<4 then Some(a.[n]) else None //(int -> string option)
match fG 3 with
Some n->printfn "fG returned %A" n
|None ->printfn "Index out of range"
match fG 5 with
Some n->printfn "fG returned %A" n
|None ->printfn "Index out of range"
</lang>
{{out}}
<pre>
4
fN returned <null>
null
fN returned Some "g"
Value not found
fN returned 3
fG returned "e"
Index out of range
</pre>