Part 3

# Defining stuff

``````let count = 1
let add x y = x + y

let v = 2 :: Int
let h = 3 :: Float``````

# Calling functions

``````add 1 2

# List comprehensions

``[x*2 | x <- [1..10], x*2 >= 12] ``
``[ x*y | x <- [2,5,10], y <- [8,10,11]]  ``
``[x*2 | x <- [1..10]] ``

# Tuples

fst, snd, zip

## Everything has a type

``(+1) :: Int -> Int``
``(+) :: Int -> Int -> Int``

# Example

``:t (==)``

# The Eq Typeclass

## Almost all of the standard types

``(==) :: (Eq a) => a -> a -> Bool  ``

Everything before => is called a class constraint

The (==) function takes ​two values of the same type and returns a Bool.

The type of the two types must be a member of the the Eq typeclass,

# The elem function

## has the type

``elem :: (Eq a) => a -> [a] -> Bool``

# Example

``````data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun
deriving (Eq)``````
``Mon == Fri``
``Fri /= Wed``

# The Ord Typeclass

## for types that have ordering

``(<) :: (Ord a) => a -> a -> Bool  ``
``:t (<)``

# Example

``````data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun
deriving (Eq, Ord)``````
``Mon > Fri``
``Fri > Wed``

# Example

``````data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun
deriving (Enum)``````
``[Mon..Fri]``
``succ Fri``
``pred Fri``

# The Show Typeclass

## Example

``````data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun
deriving (Show)``````
``show Fri``

## Example

``````data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun
``read "Fri"``

# Type of a number

``13 :: (Num t) => t  ``
``:t 13``

# Whole numbers can act like

## any type that's a member of Num

``:t 13 :: Int``
``:t 13 :: Float``
``:t 13 :: Double``
``:t (+)``
``(+) :: (Num a) => a -> a -> a  ``

## So you can add numbers like so:

``(1 :: Double) + (3 :: Int)``

# Functor

is just another typeclass

# The Maybe type

``data Maybe a = Nothing | Just a``
``````2             -- a normal value
Just 2      -- a type of context wrapping a value
Nothing -- an empty type of context``````
``````Nothing :: Maybe a
``````
``````Just :: a -> Maybe a
``````

# fmap

## fmap knows how to apply a function to a value in a context

``````> fmap (+3) (Just 2)
Just 5``````
``````> fmap (+3) Nothing
Nothing``````
``````class Functor f where
fmap :: (a -> b) -> f a -> f b``````

To make datatype f a functor

You'll need to implement this function for your data type

# Pattern Matching

``````isOne :: Int -> Bool
isOne 1 = True
isOne _ = False``````
``````pow :: Int -> Int -> Int
pow _ 0 = 1
pow a b = a^b``````
``````instance Functor Maybe where
fmap function (Just x) = Just (function x)
fmap function Nothing = Nothing  ``````
``fmap (+3) (Just 2)``
``fmap (+3) Nothing``

# Another Example

``fmap (+3) [2,4,6]``
``````instance Functor [] where
fmap = map``````

That's all folks