How can i return unit
from an expression in f#? For example:
let readInt =
let str = Console.ReadLine()
let (succ, num) = Int32.TryParse(str)
match succ with
| true -> Some(num)
| _ -> None
match readInt with
| Some(v) -> Console.WriteLine(v)
| None -> ignore //i don't want to do anything,
// but i don't know how to ignore this brunch of the expression
The value of the unit type is often used in F# programming to hold the place where a value is required by the language syntax, but when no value is needed or desired. An example might be the return value of a printf function.
Unlike C#, F# has no return keyword. The last expression to be evaluated in the function determines the return type. Also, from the FSI output above, it shows the function square has signature int -> int, which reads as “a function taking an integer and returning an integer”.
The (only possible) unit value in F# is written as
()
So your code becomes
...
| None -> ()
Just write ()
as follows
match readInt with
| Some(v) -> Console.WriteLine(v)
| None -> ()
Keep in mind the unit value ()
, it is handy in many situations.
In this case, you could use iter
function from Option module:
Option.iter Console.WriteLine readInt
It also highlights the fact that iter
functions (e.g. those from Seq
, List
and Array
module) will always give you the unit value ()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With