如何从f#中的表达式返回单位

Dzm*_*voi 8 f# unit-type

我如何unit从f#中的表达式返回?例如:

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
Run Code Online (Sandbox Code Playgroud)

rkh*_*rov 15

F#中的(仅可能)单位值写为

()
Run Code Online (Sandbox Code Playgroud)

所以你的代码变成了

...
| None -> ()
Run Code Online (Sandbox Code Playgroud)


Joh*_*mer 7

请写()如下

match readInt with
    | Some(v) -> Console.WriteLine(v)
    | None -> ()
Run Code Online (Sandbox Code Playgroud)


pad*_*pad 5

请记住单位价值(),在许多情况下都很方便.

在这种情况下,您可以使用Option模块中的iter功能:

Option.iter Console.WriteLine readInt
Run Code Online (Sandbox Code Playgroud)

它还强调一个事实,即iter功能(例如那些Seq,ListArray模块)将永远给你的单位值().