如何正确使用|>操作员? [英] how to correctly use |> operator?
问题描述
当我尝试在榆木中使用 |>
运算符时出现错误
i get an error when i try use the |>
operator in elm
kl : List Float
kl =
List.map toFloat (List.range 1 10)
kll : Float
kll =
let
half x =
x / 2
in
List.sum (List.map half (List.map toFloat (List.range 1 10)))
下面的代码我使用 |>
并得到错误:
The code below i use the |>
and get an error:
klpipe : List Float
klpipe =
1 10 |> List.range |> toFloat |> List.map
推荐答案
|> ;
只能用于将左侧的单个参数应用于右侧的函数。以下是一些示例,可以让您直观地了解其工作原理:
|>
can only be used to apply a single argument on the left side to a function on the right side. Here's a few examples to give you an intuition of how it works:
x |> f == f x
y |> f x == f x y
f x |> g == g (f x)
您可以使用<将多个参数应用于单个函数code> |> ,但是您必须一次以反转顺序执行一次,并使用括号违背其自然的关联性:
You can apply multiple arguments to a single function using |>
, but you'll have to do it one at a time in revers order and use parentheses to go against its natural associativity:
10 |> (1 |> List.range) |> (toFloat |> List.map)
此处带括号的表达式都评估为适合函数。在管道的右侧。没有括号, 1 |> 10 |> List.range
等同于`List.range(10 1)。
Here the parenthesized expressions both evaluate to functions that "fit" on the right side of the pipe. Without parentheses, 1 |> 10 |> List.range
would be equivalent to `List.range (10 1).
但是我不觉得这很可读,而是使用管道
I don't find this very readable however, and would instead use the pipe operator much more sparingly:
List.range 1 10 |> List.map toFloat
仅仅因为您可以使它看起来像钉子,并不意味着您应该在上面用锤子
Just because you can make it look like a nail doesn't mean you should use a hammer on it.
这篇关于如何正确使用|>操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!