## Selection: A or B?

#### Haskell: guards for general conditionals

getWord [] = []

getWord a:x

| elem a whitespace = []

| otherwise = a : getWord x

## Selection: One of Many

#### Haskell: case uses pattern matching

count Leaf = 0

count Node _ t1 t2 = 1 + count t1 + count t2

count' t = case t of

Leaf = 0

Node _ t1 t2 = 1 + count t1 + count t2

## Iteration and Recursion

#### Easiest transformation of recursion to iteration is in case of tail recursion: No computation follows recursive call

getWord [] = []

getWord a:x

| elem a whitespace = []

| otherwise = a : getWord x

#### Explicit specification of order of operations

return :: a -> m a

(>>=) :: m a -> (a -> m b) -> m b

#### Satisfying

return a >>= f = f a

m >>= return = m

m >>= (\a -> ((f a) >>= g)) = (m >>= f) >>= g

## Compare

sumT' Leaf = 0

sumT' (Node n t1 t2) =

return n >>= \num ->

sumT' t1 >>= \s1 ->

sumT' t2 >>= \s2 ->

return (num + s1 + s2)

#### Java

class Node extends Tree {

int sumT() {

int num = number();

int s1 = left.sumT();

int s2 = right.sumT();

return num + s1 + s2; }; //....

## Monads Can Model Parallelism vs Serialization

#### E.g., server and client pair

server:: Message t -> IO t

server order = log order >>= show order

client:: IO t -> Message t

## Race conditions

#### Consider:

public class Racer extends Thread {

public static int a;

protected class R1 extends Thread {

public void run() { a = 1; } };

protected class R2 extends Thread {

public void run() { a = 2; } };

public void run() {

R1 r1 = new R1; R2 r2 = new R2;

r1.start(); r2.start(); yield();

r1.join(); r2.join();

java.io.System.out.println(a); }; };