25.10.2015 Views

Write You a Haskell Stephen Diehl

1kEcQTb

1kEcQTb

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

length :: [a] -> Int<br />

length [] = 0<br />

length (x:xs) = 1 + (length xs)<br />

fst :: (a, b) -> a<br />

fst (a,b) = a<br />

Patterns may be guarded by predicates (functions which yield a boolean). Guards only allow the execution<br />

of a branch if the corresponding predicate yields True.<br />

filter :: (a -> Bool) -> [a] -> [a]<br />

filter pred [] = []<br />

filter pred (x:xs)<br />

| pred x = x : filter pred xs<br />

| otherwise = filter pred xs<br />

Recursion<br />

In <strong>Haskell</strong> all iteration over data structures is performed by recursion. Entering a function in <strong>Haskell</strong><br />

does not create a new stack frame, the logic of the function is simply entered with the arguments on the<br />

stack and yields result to the register. In the case where a function returns an invocation of itself invoked<br />

in the tail position the resulting logic is compiled identically to while loops in other languages, via a jmp<br />

instruction instead of a call.<br />

sum :: [Int] -> [Int]<br />

sum ys = go ys 0<br />

where<br />

go (x:xs) i = go xs (i+x)<br />

go [] i = i<br />

Functions can be defined to recurse mutually on each other.<br />

even 0 = True<br />

even n = odd (n-1)<br />

odd 0 = False<br />

odd n = even (n-1)<br />

Laziness<br />

A <strong>Haskell</strong> program can be thought of as being equivalent to a large directed graph. Each edge represents<br />

the use of a value, and each node is the source of a value. A node can be:<br />

17

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!