Hugonweb | Haskell Tips

Cheatsheet

Symbol Description
$ Use in place of parenthesis for function calls/applicatives/etc. a (b c) = a $ b c
. Function composition, useful in the "point free style" with no arguments f = g . h
liftIO When you have something that returns an IO monad f, and you want to put it where some other (but containing IO) monad should be, then you can do liftIO f. It converts an IO monad into the required monad if compatible.
<$> Shorthand for fmap; maps a function taking plain old types onto data wrapped in a functor, applicative, or monad, returning wrapped contents
<*> Similar to <$>, but also the function is wrapped in an applicative, just like the arguments and result
sequenceA flips around applicatives e.g. turns a list of Maybe into Just a list or Nothing
traverse Applicative f => (a -> f b) -> t a -> f (t b) maps a function reurning an applicative and then flips the applicative outside of the e.g. list

With applicatives, you can do

(*) <$> (Just 3) <*> (Just 4)

and just add another <*> (Just 5) if the initial function takes 3 arguments, and so on.

Examples with lists

> let x = [1,2,3]
> let y = Just <$> x
> y
[Just 1,Just 2,Just 3]
> let z = Nothing : y
> z
[Nothing,Just 1,Just 2,Just 3]
> sequenceA y
Just [1,2,3]
> sequenceA z
Nothing
> traverse Just x
Just [1,2,3]

Applicatives and Monads

After Haskell made Monad a subclass of Applicative, you can always use the new (applicative or functor) name for all of these:

All copied from https://entropicthoughts.com/haskell-procedural-programming#things-you-never-need-to-care-about by Christoffer Stjernlöf

On the other hand, using these most general functions can make error messages more confusing when using lists. Concatenation with ++ instead of <> (from Semigroup) and mapping with map instead of fmap or <$> (from Functor) can be more readable and simpler when working with a list of monads/applicatives/etc. But beware that ++ doesn't work with Text, <> must be used!

Do Notation

In the Monad do notation,

do 
    a <- as
    bs a

Translates to as >>= bs.

Modules

If you defined a data type, then this only exports the type constructor:

module XXX
    (
        MyDatatype
    )

This exports the data constructor (and accessor functions for a record) as well:

module XXX
    (
        MyDatatype (..)
    )