F# 如果为 null,则返回空字符串

标签 f#

我正在尝试通过开发一个小型“网络爬虫”来接触一些 F# 语言。我有一个这样声明的函数:

let results = HtmlDocument.Load("http://joemonster.org//")

let images = 
results.Descendants ["img"]
|> Seq.map (fun x -> 
    x.TryGetAttribute("src").Value.Value(),
    x.TryGetAttribute("alt").Value.Value()
)

这当然应该为我返回“img”标签的“src”“alt”属性的映射。但是,当我遇到标签中缺少其中一个的情况时,我收到一个异常,TryGetAttribute 返回 null。我想更改该函数以返回属性值或空字符串(如果为 null)。 我已经尝试过 this ticket 的答案但没有成功。

最佳答案

TryGetAttribute 返回一个 option 类型,当它为 None 时,您无法获取其 -相反,你会得到一个异常(exception)。您可以针对返回的选项值进行模式匹配,并针对 None 情况返回空字符串:

let getAttrOrEmptyStr (elem: HtmlNode) attr =
  match elem.TryGetAttribute(attr) with
  | Some v -> v.Value()
  | None -> ""
let images = 
  results.Descendants ["img"]
  |> Seq.map (fun x -> getAttrOrEmptyStr x "src", getAttrOrEmptyStr x "alt")

或者使用defaultArgOption.map的版本:

let getAttrOrEmptyStr (elem: HtmlNode) attr =
  defaultArg (elem.TryGetAttribute(attr) |> Option.map (fun a -> a.Value())) ""

或者现在存在 Option.defaultValue 的另一个选项,并使用 HtmlAttribute.value 函数进行简洁的 Option.map 调用:

let getAttrOrEmptyStr (elem: HtmlNode) attr =
  elem.TryGetAttribute(attr)
  |> Option.map HtmlAttribute.value
  |> Option.defaultValue ""

关于F# 如果为 null,则返回空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49220141/

相关文章:

内部函数的 F# 泛型

asynchronous - 在异步上下文中读取文件?

wpf - 如何将命令/属性绑定(bind)到 FSharp.ViewModule 中的 PropertyChanged

f# - 从 F# 实例化 C# 9 记录

F#使用while循环

F# powerpack 和分发

web-services - 使用 F# WsdlService 类型提供程序编译错误

f# - 在F#中结合功能和管道运算符

c# - 从 C# 调用高阶 F# 函数

macos - 为什么我没有使用此 F# 代码在 OSX 上获得输出,但我在 Windows 上获得了输出