将 Pipe Forward 与嵌套序列一起使用

Using Pipe Forward with nested sequences

我是 F# 的新手,所以如果我使用了不正确的名称,我深表歉意。

我正在尝试使用 F# 解析如下所示的网页:

<!--This is simplified, in reality there are more divs, anchors etc. -->
<html>
<body> 
    <div class="pr-single"><a href="http://google.ca">Google</a></div>
    <div class="pr-single"><a href="http://apple.com">Apple</a></div>
    <div class="pr-single"><a href="http://microsoft.com">Microsoft</a></div>
</body>
</html>

我已经声明了一个类型

type PromoterPage = FSharp.Data.HtmlProvider<"http://somewebpage.com">

现在我正在尝试获取页面上所有链接的列表。我的思考过程是:

  1. 通过class名称获取所有外部div
  2. 获取所有这些 div 的后代
  3. 将这些后代收集到一个平面列表中
  4. 将此列表过滤为仅 <a> 个标签

我的尝试如下:

let GetFirst (page:PromoterPage) = 
    page.Html.Descendants()
    |> Seq.filter(fun n -> n.HasClass("pr-single"))                 //Find the divs
    |> Seq.map(fun n -> n.Descendants())                            //Get the descendants
    |> Seq.collect(fun n -> n |> Seq.where(fun m -> m.HasName("a")) //Filter and collect the anchors

问题似乎是您不能嵌套 Seq 函数或者我做的不正确。我收到错误:

Incomplete values or function definition. If this is an expression, the body of the expression must be indented to the same column as the keyword.

我可以嵌套 Seq 函数吗?我是不是想错了?

您缺少右括号:

|> Seq.collect(fun n -> n |> Seq.where(fun m -> m.HasName("a")))

Can I nest Seq functions the way I'm trying to here?

是的,在 lambda 中使用管道嵌套函数是完全没问题的。但是,我经常将它们拉出到本地函数中,因为它可以使代码在长 运行.

中更具可读性