如何在给定条件下执行操作?

How can I do an action on a given condition?

我正在尝试将 doIf 函数从 C# 移植到 F#。

这是 C# 代码:

static void DoIf(bool c, Action f)
{
    if (c) {
        f();
    }
}

这是我的猜测:

let doIf (c: bool) (f: unit -> unit) :unit = 
    if c
    then f ()
    else ???

如果我写 doIf true (fun _ -> printfn "hello"),它会打印 hello.

但我不确定我应该如何处理 else 来满足表达式。

您正在寻找()

let doIf (c: bool) (f: unit -> unit) :unit = 
    if c
    then f ()
    else ()

doIf true (fun _ -> printfn "hello")

Try it online!

虽然@aloisdg 提供的答案是正确的,但实际上您不需要显式 return unit if c = false。此外,不需要类型注释。我会选择

let doIf c f = if c then f()

现在我要问自己的问题是我是否真的需要这个功能。例如,在您的示例中,没有 doIf 功能的字符数实际上少于带有功能的字符数,我个人认为它也更容易阅读

doIf true (fun _ -> printfn "hello")
if true then printfn "hello"