【问题标题】:Pattern matching during pipe管道期间的模式匹配
【发布时间】:2016-04-23 15:49:02
【问题描述】:

我要解析一个 xml 文档,从一个 xml 节点中提取一个整数。

目前我有:

try do
  Floki.find(node, "stat[type='jersey_num']")
    |> Floki.text
    |> Integer.parse
    |> elem(0)
rescue
  e -> nil
end

效果很好,但我不喜欢拯救一切,我想做类似的事情:

Floki.find(node, "stat[type='jersey_num']")
  |> Floki.text
  |> case Integer.parse do
    { int, _binary } -> int
    _                -> nil
  end

但我在第四行得到unhandled operator ->,有没有办法做到这一点?

【问题讨论】:

    标签: elixir


    【解决方案1】:

    您需要先通过管道输入Integer.parse,然后再输入case

    defmodule MyInteger do
      def parse(string) do
        string
        |> Integer.parse
        |> case do
             {int, _} -> int
             _ -> nil
           end
      end
    end
    

    演示:

    iex(1)> MyInteger.parse "123"
    123
    iex(2)> MyInteger.parse "abc"
    nil
    

    请注意MyInteger.parse "123abc" #=> 123,因此如果您想要与Integer.parse/1 相同的行为,您可能希望将模式匹配更改为{int, ""} -> int

    【讨论】:

    • 只要确保将 case 表达式放入它自己的函数中即可。为了便于阅读,管道表达式不应超过一行。
    • @tkowal 即使是最后一行?有时就像在这种情况下,你匹配要么返回一些东西(也许再次管道)或完全退出
    • case do {int, _} -> int; _ -> nil end 单线获胜!来自:Elixir case on a single line.
    • 很好,这正是我想要做的。虽然我想说写case Integer.parse(string) do 的可读性略高。管道很棒,但你可以过度使用它们!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多