3 ms·
Let's have a talk about the $ operator. When you use it more than once per line, you're writing code that looks weird and is hard to read. Switch to the simil
by jrockway 15y ago
Let's have a talk about the $ operator. When you use it more than once per line, you're writing code that looks weird and is hard to read. Switch to the similar function-composition operator, and everything looks more idiomatic.
Instead of:
fibServer x = quickHttpServe $ writeBS $ B.pack $ show (fibonacci x)
Just write:
fibServer = quickHttpServe . writeBS . B.pack . show . fibonacci
The case for $ is where you want application instead of composition:
fibOf42Server = quickHttpServe . writeBS . B.pack . show . fibonacci $ 42
I even write things like:
main = print =<< foo
instead of
main = foo >>= print
for consistency.
Anyway, it's a little style thing, but it's nice to use the composition operator (.) when you want composition and the application operator ($) when you want application. It makes the code look nicer and it shows its intent more clearly. And really, they are different concepts, even if they both type-check the same.
And finally, remember that function application, by default, is the highest-precedence operator in Haskell. When you write:
foo . (bar 42) . baz
It's the same as:
foo . bar 42 . baz
Because of operator precedence. $ only exists to change the order of operations for a particular expression.
- Peaker 15y agoI'll add that a nice little benefit of using: a . b . c . d $ e over: a $ b $ c $ d $ e is that any sub-expression taken from the first expression is valid and can be refactored out into its own name. (.) is associative and ($) is not.
- bobfunk 15y agoReally interesting style comment. Will keep this in mind.