Tony Locke‎ > ‎

Haskell

An aide memoire.

l = [1, 2, 3]

All elements must be of same type. Length doesn't affect the type.

areaCirc r = pi * r^2

Type names always start with a capital letter.

Parametric polymorphism (generics)
length :: [a] -> Int

Type constraint after :: and before => 
(+) :: (Num a) => a -> a -> a

Num is a typeclass.

Guards

mySignum x | x < 0 = -1 | x > 0 = 1 | otherwise = 0


Pattern matching
pts :: Int -> Int pts 1 = 10 pts 2 = 6 pts 3 = 4 pts 4 = 3 pts 5 = 2 pts 6 = 1 pts _ = 0


Where


log2 x = higher x 0 where higher x n | power 2 n > x = n - 1 | otherwise = higher x (n + 1)

map 
{- higher order function (has a function as an argument) -}

Modules

import Data.List

foldr f acc xs -- fold right associative
foldl -- left associative

foldl' -- eager evaluation
foldr1 -- use last element as initial accumulator

Lists

init -- all but last element

List Comprehensions

evensMinusOne es = [n - 1 | n <- es, isEven n]

Data

data Anniversary = Birthday String Int Int Int -- name, year, month, day | Wedding String String Int Int Int -- spouse name 1, spouse name 2, year, month, day

As patterns

contrivedMap f list@(x:xs) = f list x : contrivedMap f xs

Do

main = do
putStrLn "What's your first name?"
firstName <- getLine
putStrLn "What's your last name?"
lastName <- getLine
let bigFirstName = map toUpper firstName
bigLastName = map toUpper lastName
putStrLn $ "hey " ++ bigFirstName ++ " " ++ bigLastName ++ ", how are you?"
Comments