将“快速管道”操作符与many places中的“管道最后”进行比较的方式意味着它们是彼此的替代品。想要将值作为最后一个参数发送给函数吗?最后使用管道(|>
)。想把它作为第一个参数发送?使用快速管道(曾几何时|.
,现在弃用->
)。
因此,正如我在今天早些时候所做的那样,你会想到以下代码可以让你获得正则表达式匹配中的第一个匹配:
Js.String.match([%re "/(\\w+:)*(\\w+)/i"], "int:id")
|> Belt.Option.getExn
-> Array.get(1)
但你错了(再次,就像我今天早些时候......)
相反,编译器会发出以下警告:
We've found a bug for you!
OCaml preview 3:10-27
This has type:
'a option -> 'a
But somewhere wanted:
'b array
见this sandbox。是什么赋予了?
看起来他们搞砸了->
的优先权,所以它实际上被解释为
Js.String.match([%re "/(\\w+:)*(\\w+)/i"], "int:id")
|> (Belt.Option.getExn->Array.get(1));
运营商内联:
Array.get(Belt.Option.getExn, 1, Js.String.match([%re "/(\\w+:)*(\\w+)/i"], "int:id"));
或者部分应用程序更明确,因为Reason的语法在currying方面有点混乱:
let f = Array.get(Belt.Option.getExn, 1);
f(Js.String.match([%re "/(\\w+:)*(\\w+)/i"], "int:id"));
用->
替换|.
作品。正如用|>
取代|.
一样。
我认为这是Reason中的一个错误,但无论如何都会建议不要使用“快速管道”,因为它会引起很多混乱而且收效甚微。
另请参阅此discussion on Github,其中包含各种变通方法。留下@ glennsl作为公认的答案,因为它描述了问题的本质。
更新:还有an article on Medium深入探讨了“数据优先”和“数据最后”的优缺点,因为它适用于Ocles / Reason with Bucklescript。