CheatSheet Haskell
CheatSheet Haskell
case, class, data, deriving, do, “Layout” rule, braces and semi-colons.
else, if, import, in, infix, infixl, Numbers
Haskell can be written using braces and semi-
infixr, instance, let, of, module, 1 - Integer colons, just like C. However, no one does. Instead,
newtype, then, type, where 1.0, 1e10 - Floating point the “layout” rule is used, where spaces represent
instance Def Bool where List Comprehensions There are very few predefined “operators” in
defValue _ = False Haskell - most that do look predefined are actu-
A list comprehension consists of three types of el- ally syntax (e.g., “=”). Instead, operators are simply
ements - generators, guards, and targets. A list com- functions that take two arguments and have special
instance Def Char where
prehension creates a list of target values based on syntax support. Any so-called operator can be ap-
defValue _ = ' '
the generators and guards given. This comprehen- plied as a normal function using parentheses:
Maybe is a littler trickier, because we want to get sion generates all squares:
a default value for the type, but the constructor 3 + 4 == (+) 3 4
squares = [x * x | x <- [1..]]
might be Nothing. The following definition would To define a new operator, simply define it as a nor-
work, but it’s not optimal since we get Nothing x <- [1..] generates a list of all Integer values mal function, except the operator appears between
when Nothing is passed in. and puts them in x, one by one. x * x creates each
the two arguments. Here’s one which takes inserts
element of the list by multiplying x by itself.
instance Def a => Def (Maybe a) where a comma between two strings and ensures no extra
Guards allow certain elements to be excluded.
defValue (Just x) = Just (defValue x) spaces appear:
The following shows how divisors for a given num-
defValue Nothing = Nothing ber (excluding itself) can be calculated. Notice how first ## last =
We’d rather get a Just (default value) back instead.
d is used in both the guard and target expression. let trim s = dropWhile isSpace
Here is where a lazy pattern saves us – we can pre- divisors n = (reverse (dropWhile isSpace
tend that we’ve matched Just x and use that to get [d | d <- [1..(n `div` 2)] (reverse s)))
a default value, even if Nothing is given: , n `mod` d == 0] in trim last ++ ", " ++ trim first
instance Def a => Def (Maybe a) where Comprehensions are not limited to numbers. Any > " Haskell " ## " Curry "
defValue ~(Just x) = Just (defValue x) list will do. All upper case letters can be generated: Curry, Haskell
1 git://github.com/m4dc4p/cheatsheet.git
2 http://hackage.haskell.org/cgi-bin/hackage-scripts/package/CheatSheet
3 http://blog.codeslower.com