Elm piping

2020-07-29

I have been fiddling a little with Elm and looking through manual and some guides. It is first functional programming language that I am experiencing and there is lots of new concepts. But now I'm presenting you few operators of the Elm. Some might call them pizza operators, not because of the taste but the shape!

Piping

Here is the original example code that is not using piping at all. padLeft is from Elm's Core package, String. Code does get the minutes from seconds, so e.g 280 seconds is 4 minutes. And it will add padding zero to start so that it always has 00 if no minutes yet or e.g 01 when one minute has passed.

The code is indented as the elm-format did format it in the editor.

secondsToMinutes : Int -> String
secondsToMinutes seconds =
    padLeft 2 '0' (String.fromInt (floor (toFloat seconds / 60)))

-- example how to use this
secondsToMinutes 280
-- result is "04"

|> Forwards pipe

secondsToMinutes : Int -> String
secondsToMinutes seconds =
    (seconds |> toFloat)
        / 60
        |> floor
        |> String.fromInt
        |> padLeft 2 '0'

<| Backwards pipe

secondsToMinutes : Int -> String
secondsToMinutes seconds =
    padLeft 2 '0' <|
        String.fromInt <|
            floor <|
                toFloat seconds
                    / 60

Simpler <| example

You can use backwards pipe to replace parentheses like in the following case. This example is just for demo purpose, of course you can do the String.fromInt in the function but that is not the point of this.

cat : String -> String -> String
cat name age =
  "Cat name is " ++ name ++ " and it's " ++ age ++ " years old."

cat "Jackie" (String.fromInt 8)
-- This is same as:
cat "Jackie" <| String.fromInt 8

Source

I asked the naming for the operators from the helpful Elm Slack, I suggest you to join if you are interested of Elm!

Links to docs:

  • elm
  • piping
  • operator
  • functional