鉴于 F# 中的以下记录:
type Model =
{ Text: string option }
Run Code Online (Sandbox Code Playgroud)
什么是 C# 的 F# 等价物,
string.IsNullOrEmpty(Model.Text)
Run Code Online (Sandbox Code Playgroud)
TIA
假设您想将一个None值视为 null 或空,您可以使用Option.fold:
let m = { Text = Some "label" }
m.Text |> Option.fold (fun _ s -> String.IsNullOrEmpty(s)) true
Run Code Online (Sandbox Code Playgroud)
使用的一个缺点fold是在累加器函数中忽略了累加器参数。在这种情况下,您只需要一个函数来应用,Some如果选项是None例如,则需要一个默认值来使用
let getOr ifNone f = function
| None -> ifNone
| Some(x) -> f x
Run Code Online (Sandbox Code Playgroud)
然后你可以使用
m.Text |> getOr true String.IsNullOrEmpty
Run Code Online (Sandbox Code Playgroud)
Lees 的答案可能是功能上最惯用的,即当您想要处理数据类型时,您可以使用折叠将其压缩为答案。但请注意,您可以删除“s”,使其成为
m.Text |> Option.fold (fun _ -> String.IsNullOrEmpty) true
Run Code Online (Sandbox Code Playgroud)
如果折叠还不是你所熟悉的事情,那么一个更面向集合的版本将是,“它们都是空的吗?” (如果没有,那就有)
m.Text |> Option.forall (fun s -> String.IsNullOrEmpty s)
Run Code Online (Sandbox Code Playgroud)
或简称
m.Text |> Option.forall String.IsNullOrEmpty
Run Code Online (Sandbox Code Playgroud)
(我个人会用这个)