15

In Haskell, you can use the $ operator to clean up bits of code, removing the need for parens.

Does elm support this operator, or something like it?

I can define it myself but I was hoping that this was something built-in.

Here's how it works:

import Html
import List exposing (map, foldr)

datas = [("a", 1), ("b", 2), ("c", 3)]

{--}
($) : (a -> b) -> (a -> b)
($) a b = a b
infixr 0 $
--}

main =
  {-- replace all these parens
  Html.text (toString (foldr (++) "" (map fst datas)))
  --}
  Html.text $ toString $ foldr (++) "" $ map fst datas
Conrad.Dean
  • 4,341
  • 3
  • 32
  • 41

1 Answers1

24

Yes, we use <| instead of $. We borrowed it from F# along with the flipped version |> and << for composition . and the flipped version >>.
Once these were introduced, people naturally gravitated towards a style dubbed 'pipelining', where you take some data and transform it in a couple of steps using the |> operator. These days this is a more common code pattern in Elm code than using <|.

For example:

update : (Float, Keys) -> Model -> Model
update (dt, keys) mario =
  mario
  |> gravity dt
  |> jump keys
  |> walk keys
  |> physics dt

(Taken from the Mario example on the website)

Michael Martin-Smucker
  • 11,927
  • 7
  • 31
  • 36
Apanatshka
  • 5,958
  • 27
  • 38
  • 1
    Nice. I had seen this in the docs but hadn't made the connection how you could clean stuff up with it in the same way. I'd definitely want to use `|>` and read my code forwards than `$` and have to read my code backwards – Conrad.Dean Dec 07 '15 at 13:17
  • also, this is called the "thrush" operator in clojure, but it's implemented an infix operator over curried functions instead of as a macro. – Conrad.Dean Dec 14 '15 at 15:28