Skip to content

Commit 29efb12

Browse files
committed
Simplify (<|) and (|>) examples and add usage warnings
1 parent 4af69dc commit 29efb12

File tree

1 file changed

+17
-26
lines changed

1 file changed

+17
-26
lines changed

src/Basics.elm

Lines changed: 17 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -842,32 +842,31 @@ composeR f g x =
842842
{-| Saying `x |> f` is exactly the same as `f x`.
843843
844844
It is called the “pipe” operator because it lets you write “pipelined” code.
845-
For example, say we have a `toRadians` function for turning user input in
846-
degrees into radians. We can rewrite it like this:
845+
For example, say we have a `sanitize` function for turning user input in
846+
degrees into integers. We can rewrite it like this:
847847
848848
import Maybe
849-
import String
850849
851850
-- BEFORE
852-
toRadians : String -> Float
853-
toRadians input =
854-
degrees (toFloat (Maybe.withDefault 0 (String.toInt input))
851+
sanitize : String -> Maybe Int
852+
sanitize input =
853+
String.toInt (String.trim input)
855854
856855
-- AFTER
857-
toRadians : String -> Float
858-
toRadians input =
856+
sanitize : String -> Maybe Int
857+
sanitize input =
859858
input
859+
|> String.trim
860860
|> String.toInt
861-
|> Maybe.withDefault 0
862-
|> toFloat
863-
|> degrees
864861
865-
Once you get the hang of it, it can be quite nice! To get a better intuition,
866-
I recommend trying to rewrite code that uses `x |> f` into code like `f x`
867-
until there are no pipes left.
862+
To get a better intuition, I recommend trying to rewrite code that uses `x |> f`
863+
into code like `f x` until there are no pipes left.
868864
869-
**Note:** The compiler rewrites this to normal function application, so `(|>)`
870-
has no runtime overhead.
865+
**Note:** This can be overused! I think folks find it quite neat, but when you
866+
have three or four steps, the code often gets clearer if you break out a
867+
top-level helper function. Now the transformation has a name. The arguments are
868+
named. It has a type annotation. It is much more self-documenting that way!
869+
Testing the logic gets easier too. Nice side benefit!
871870
-}
872871
apR : a -> (a -> b) -> b
873872
apR x f =
@@ -876,16 +875,8 @@ apR x f =
876875

877876
{-| Saying `f <| x` is exactly the same as `f x`.
878877
879-
It can help you avoid parentheses, which can be nice sometimes. For example:
880-
881-
Maybe.withDefault 0 (String.toInt "123")
882-
883-
Can be written as:
884-
885-
Maybe.withDefault 0 <| String.toInt "123"
886-
887-
**Note:** The compiler rewrites this to normal function application, so `(<|)`
888-
has no runtime overhead.
878+
It can help you avoid parentheses, which can be nice sometimes. Maybe you want
879+
to apply a function to a `case` expression? That sort of thing.
889880
-}
890881
apL : (a -> b) -> a -> b
891882
apL f x =

0 commit comments

Comments
 (0)