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

时间:2018-03-11 12:46:43

标签: 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的答案,但没有成功。

1 个答案:

答案 0 :(得分:4)

go test -bench . 会返回选项类型,当它为goos: darwin goarch: amd64 BenchmarkFunc-2 5000000 360 ns/op 120 B/op 4 allocs/op PASS ok command-line-arguments 2.190s 时,您无法获取 - 而是会收到异常。您可以对返回的选项值进行模式匹配,并为TryGetAttribute大小写返回一个空字符串:

None

使用Nonelet 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") 的版本:

defaultArg

或另一个选项现在Option.map存在,并使用let getAttrOrEmptyStr (elem: HtmlNode) attr = defaultArg (elem.TryGetAttribute(attr) |> Option.map (fun a -> a.Value())) "" 函数进行简短的Option.defaultValue调用:

HtmlAttribute.value