【问题标题】:Using Pipe Forward with nested sequences将 Pipe Forward 与嵌套序列一起使用
【发布时间】:2016-08-04 22:05:13
【问题描述】:

我是 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. 按类名获取所有外层div
  2. 获取所有这些 div 的后代
  3. 将这些后代收集到一个平面列表中
  4. 将此列表过滤为仅&lt;a&gt; 标签

我的尝试如下:

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 函数吗?我是否以错误的方式思考这个问题?

【问题讨论】:

    标签: f# seq


    【解决方案1】:

    您缺少右括号:

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

    我可以按照我在这里尝试的方式嵌套 Seq 函数吗?

    是的,在 lambdas 中使用管道嵌套函数是非常好的。但是,我经常将它们提取到本地函数中,因为从长远来看它可以使代码更具可读性。

    【讨论】:

    • 哇,太尴尬了。 :) 谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-06-01
    • 2011-09-18
    • 1970-01-01
    • 2017-01-24
    • 2017-02-28
    • 2013-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多