Haskell operators I have trouble with

April 19, 2017

The Haskell $, . , and => operators.

A census bureau operator and his machine. class=
A Census Bureau operator © 1908 Waldon Fawcett for Library of Congress

$

Replaces parentheses.

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
    
  1. a function that maps type a to type b
  2. a value of type a
  3. 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.

For example, (==) :: (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 a that is an instance of FromJSON
  • you have (=>)
  • an operation named jsonData, which returns an ActionM a

And this one is is not an operator, as it doesn’t have a type:


    Prelude> :t (=>)
    :1:2: error: parse error on input ‘=>’
    

Tags: haskell