与空序列匹配

问题描述 投票:5回答:4

我正在学习F#,我开始使用序列和match表达式。

我正在编写一个Web浏览器,它通过类似于以下内容的HTML进行查看,并使用<span>类在父级paging中获取最后一个URL。

<html>
<body>
    <span class="paging">
        <a href="http://google.com">Link to Google</a>
        <a href="http://TheLinkIWant.com">The Link I want</a>
    </span>
</body>
</html>

我尝试获取最后一个URL如下:

type AnHtmlPage = FSharp.Data.HtmlProvider<"http://somesite.com">

let findMaxPageNumber (page:AnHtmlPage)= 
    page.Html.Descendants()
    |> Seq.filter(fun n -> n.HasClass("paging"))
    |> Seq.collect(fun n -> n.Descendants() |> Seq.filter(fun m -> m.HasName("a")))
    |> Seq.last
    |> fun n -> n.AttributeValue("href")

但是,当我正在搜索的课程缺少页面时,我遇到了问题。特别是我得到了ArgumentExceptions消息:Additional information: The input sequence was empty.

我的第一个想法是构建另一个匹配空序列的函数,并在页面上找不到paging类时返回一个空字符串。

let findUrlOrReturnEmptyString (span:seq<HtmlNode>) =
    match span with 
    | Seq.empty -> String.Empty      // <----- This is invalid
    | span -> span
    |> Seq.collect(fun (n:HtmlNode) -> n.Descendants() |> Seq.filter(fun m -> m.HasName("a")))
    |> Seq.last
    |> fun n -> n.AttributeValue("href")

let findMaxPageNumber (page:AnHtmlPage)= 
    page.Html.Descendants()
    |> Seq.filter(fun n -> n.HasClass("paging"))
    |> findUrlOrReturnEmptyStrin

我现在的问题是Seq.Empty不是文字,不能用于模式。大多数具有模式匹配的示例在其模式中指定空列表[],因此我想知道:我如何使用类似的方法并匹配空序列?

f# pattern-matching seq guard-clause
4个回答
10
投票

ildjarn在评论中给出的建议是一个很好的建议:如果你觉得使用match会创建更可读的代码,那么制作一个活动模式来检查空seqs:

let (|EmptySeq|_|) a = if Seq.isEmpty a then Some () else None

let s0 = Seq.empty<int>

match s0 with
| EmptySeq -> "empty"
| _ -> "not empty"

在F#interactive中运行它,结果将是"empty"


9
投票

您可以使用when警卫进一步限定案件:

match span with 
| sequence when Seq.isEmpty sequence -> String.Empty
| span -> span
|> Seq.collect(fun (n:HtmlNode) -> n.Descendants() |> Seq.filter(fun m -> m.HasName("a")))
|> Seq.last
|> fun n -> n.AttributeValue("href")

ildjarn是正确的,在这种情况下,if...then...else可能是更可读的替代方案。


2
投票

基于@rmunn的答案,您可以制作更通用的序列相等活动模式。

let (|Seq|_|) test input =
    if Seq.compareWith Operators.compare input test = 0
        then Some ()
        else None

match [] with
| Seq [] -> "empty"
| _ -> "not empty"

1
投票

使用保护条款

match myseq with
| s when Seq.isEmpty s -> "empty"
| _ -> "not empty"
© www.soinside.com 2019 - 2024. All rights reserved.