Search code examples
functional-programmingelm

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

Solution

  • |> 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.