How to return unit from an expressions in f#
Asked Answered
M

3

13

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
Massa answered 7/8, 2013 at 6:18 Comment(0)
C
21

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

()

So your code becomes

...
| None -> ()
Commonweal answered 7/8, 2013 at 6:21 Comment(0)
C
10

Just write () as follows

match readInt with
    | Some(v) -> Console.WriteLine(v)
    | None -> ()
Cribb answered 7/8, 2013 at 6:20 Comment(0)
D
5

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

Dreamworld answered 7/8, 2013 at 8:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.