Haskell operators I have trouble with
April 19, 2017
The Haskell $, . , and => operators.
All of the following are equivalent (per Michael Steele’s answer on Stack Overflow):
putStrLn (show (1 + 1)) putStrLn (show $ 1 + 1) putStrLn $ show (1 + 1) putStrLn $ show $ 1 + 1 (putStrLn . show) (1 + 1) putStrLn . show $ 1 + 1 (putStrLn . show . (+ 1)) 1 putStrLn . show . (+ 1) $ 1
It’s type is:
Prelude> :type ($) ($) :: (a -> b) -> a -> b
- a function that maps type a to type b
- a value of type a
- output is a value of type b.
A Unix pipe for functions.
That is, feed the output of one function to the input of another.
For example, instead of
let fn x = f (g x) you can write
let fn = f . g.
Note the second version doesn’t mention
x. In this style,
you don’t mention the input variable(s).
As another example, instead of
f x = x + 1 you write
f = (+ 1).
Confusingly, this is called writing in a pointfree style. “Pointfree” as in no input variables (“points” in topology).
It’s type is:
Prelude> :type (.) (.) :: (b -> c) -> (a -> b) -> a -> c
“is an instance of”, but you read it right to left.
(==) :: (Eq a) => a -> a -> Bool is read “for every type a that is an instance of Eq”.
Type Classes and Overloading, A Gentle Introduction to Haskell, Version 98.
Here’s an example from Scotty:
jsonData :: FromJSON a => ActionM a.
Frankly, I’m still not 100% sure how to read this. My best guess is:
- For every type
athat is an instance of
- you have (
- an operation named
jsonData, which returns an
And this one is is not an operator, as it doesn’t have a type:
Prelude> :t (=>) :1:2: error: parse error on input ‘=>’
If you see an error or something that could be improved, please let me know. This is a blog about me learning, so I expect I will get some stuff wrong. The best way to reach me is by email: email@example.com (after deleting all the numbers).
To make a comment, check for a thread on the haskell subreddit and if there isn't one, then start one up.
Follow on Twitter: @mbucc
Back to the index.