首页 > 解决方案 > 如何在给定条件下执行操作?

问题描述

我正在尝试将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才能满足表达。

标签: f#

解决方案


While the answer provided by @aloisdg is as such correct, you don't actually need to explicitly return unit if c = false. Also, the type annotations aren't needed. I would go with

let doIf c f = if c then f()

Now the question I would ask myself is whether I actually need the function. In your example, for instance, the number of characters without the doIf function is actually less than with and I personally think it reads more easily as well

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

推荐阅读