Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

functional programming - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

|> 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)

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)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...