f# - 如何在给定条件下执行操作?
问题描述
我正在尝试将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
才能满足表达。
解决方案
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"
推荐阅读
- swift - Swift 获取与 _read
- c# - 如何处理异常“OpenQA.Selenium.WebDriverException”?
- python - 在时间戳 librosa 上拆分音频
- angular - 托管 Angular 应用程序路由的 MVC 应用程序不适用于第一次导航
- html - 我可以生成从 Markdown 到 html 的参考索引/书籍索引(最好是在静态站点中)吗?
- javascript - 对象中的最高值(如果有更多最大值并且它们相同,则更多)
- html - 防止父页面从锚链接滚动到子元素中的目标
- uikit - 在 SwiftUI 中,如何向 List 添加滚动刷新功能?
- django - 如果 Django 管理员也已登录,则前端在登录时收到 403 错误
- asp.net-core - 使用 Windows 身份验证创建基于角色的授权