Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return unit from an expressions in f#

Tags:

f#

unit-type

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
like image 925
Dzmitry Martavoi Avatar asked Aug 07 '13 06:08

Dzmitry Martavoi


People also ask

What is unit in f#?

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.

How do I return in F#?

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”.


3 Answers

The (only possible) unit value in F# is written as

()

So your code becomes

...
| None -> ()
like image 76
rkhayrov Avatar answered Oct 26 '22 00:10

rkhayrov


Just write () as follows

match readInt with
    | Some(v) -> Console.WriteLine(v)
    | None -> ()
like image 45
John Palmer Avatar answered Oct 26 '22 00:10

John Palmer


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 ().

like image 38
pad Avatar answered Oct 25 '22 23:10

pad