26 Oct

# Logical operators

Operators — similar to C:

``````> x = 2

> x > 1 && x < 5  -- and
True

> x > 10 || even x  -- or
True

> not (x == 100)  -- negation
True
``````

Functions — applicable to a list:

``````> :type and
and :: [Bool] -> Bool  -- Foldable t means a list of items of type t: t Bool means the type t can be converted to a Boolean

> and [x == 2, 0 < 1, True]
True

> or [x == 2, True == False, False]
True
``````

# Types

Useful in debugging

Finding the type of a variable:

``````> x :: Int; x = 10
> :type x
x :: Int

> :t 'a'  -- :t is short for :type
'a' :: Char

> :t "abc"
"abc" :: [Char]  -- or String

> :t [1, 2, 3]
[1, 2, 3] :: Num t => [t]  -- list of numbers
``````

Type of a function:

``````> increment x = x + 1
> :t increment
> increment :: Num a => a -> a  -- takes one parameter of type a (for anything) that is number-like (Num a) and returns the same type, a

> incrementAll l = [x + 1 | x <- l]
> :t incrementAll
> incrementAll :: Num t => [t] -> [t]  -- takes a list of Nums and returns the same thing
``````

Conversions:

``````> x :: Int; x = 10
> x * 0.75
<error>

> fromIntegral x * 0.75  -- Int to Double
7.5  -- type Double

> round 7.5
8  -- type Int

> intToDigit 5  -- Int to Char
'5'

> digitToInt '5'  -- Char to Int
5
``````

# Custom operators

``````(<@>) :: String -> String -> String  -- signature
x <@> y = x ++ " at " ++ y  -- definition

> "john" <@> "home"
"john at home"

(>>>) :: (a->b) -> (b->c) -> (a->c)  -- also available from Control.Arrow
f >>> g = g . f  -- composes two functions
``````

Example — take the last element (absolute value) and show the letter corresponding to its ASCII code:

``````> f = chr . abs . last
> f = last >>> abs >>> chr  -- equivalent, easier to follow
> f [-51, 49, -65]
'A'
``````

# Errors

``````incrementPositive :: Int -> Int  -- no special signature
incrementPositive x
| x >= 0		= x + 1
| x < 0		= error "Negative input"

> incrementPositive -5
Exception: Negative input
``````