functional programming and haskell - twbr away day 2011

34
Functional Programming with Haskell Adriano Bonat [email protected] @tanob

Upload: adriano-bonat

Post on 12-May-2015

289 views

Category:

Technology


4 download

DESCRIPTION

Explains why functional programming is back and shows some features from Haskell that are being ported to other languages. Presented at ThoughtWorks Brazil Away Day 2011.

TRANSCRIPT

Page 1: Functional Programming and Haskell - TWBR Away Day 2011

Functional Programming with Haskell

Adriano [email protected]

@tanob

Page 2: Functional Programming and Haskell - TWBR Away Day 2011

Why FP?

• Source of new ideas

• Expressiveness

• Multi-core CPUs

• Different paradigm

New ideas:Garbage collection (LISP)Type inference (simply typed lambda calculus)GenericsType classes

Expressiveness:DSLs

Page 3: Functional Programming and Haskell - TWBR Away Day 2011

What is it?

• Different programming paradigm

• OO

• Logic

• Procedural

• Functions are the main element in the language

Page 4: Functional Programming and Haskell - TWBR Away Day 2011

Function applications“Functional programming is so called because a program consists entirely of functions. [...]

Typically the main function is defined in terms of other functions, which in turn are defined in terms of still more functions, until at the bottom level the functions are language primitives.”

John Hughes, 1989 - Why functional programming matters

Page 5: Functional Programming and Haskell - TWBR Away Day 2011

OriginAlonzo Church developed Lambda

Calculus as part of his investigations on Math foundations

on 1936.

Page 6: Functional Programming and Haskell - TWBR Away Day 2011

Lambda Calculus

• Variables

• Expressions (e1 e2)

• Lambda abstractions (λx. e)

Page 7: Functional Programming and Haskell - TWBR Away Day 2011

Lambda Calculus (I)

• true = λxy. x

• false = λxy. y

• NOT a = (a)(false)(true)

• a AND b = (a)(b)(false)

• a OR b = (a)(true)(b)

• a XOR b = (a)((b)(false)(true))(b)

Page 8: Functional Programming and Haskell - TWBR Away Day 2011

Haskell

• Academic origin

• Named in honor of Haskell Curry

• Defined by a committee

• First version released on 98 (Haskell 98)

Page 9: Functional Programming and Haskell - TWBR Away Day 2011

Features• Pureness

• Type Inference

• Algebraic datatypes (ADTs)

• Pattern Matching

• Lazyness

• High Order Functions

• Currification (aka Partial Application)

• Type Classes

• Monads

Page 10: Functional Programming and Haskell - TWBR Away Day 2011

Pureness

• No side-effects

• A function call can have no effect other than to compute its result

• Expressions can be evaluated at any time

• Programs are “referentially transparent”

Good for:* reasoning* compiler optimization* concurrency

Page 11: Functional Programming and Haskell - TWBR Away Day 2011

Type Inference

Let’s see the types for these declarations:four = 4add x y = x + yemphasize x = x ++ “!”

Page 12: Functional Programming and Haskell - TWBR Away Day 2011

Algebraic datatypesEnumeration:data Season = Summer | Winter | Autumn | Spring

Product:data Pair = Pair Int Int

Sum:data Shape = Circle Float | Rect Float Float

Polymorfic & Recursive:data Tree a = Leaf a | Node (Tree a) (Tree a)

Page 13: Functional Programming and Haskell - TWBR Away Day 2011

Algebraic datatypes (I)

data Maybe a = Nothing | Just adata Either a b = Left a | Right b

Page 14: Functional Programming and Haskell - TWBR Away Day 2011

Pattern Matching

Definition:sum [] = 0sum (elem:rest) = elem + sum rest

Application:sum [1,2,3,10]

Page 15: Functional Programming and Haskell - TWBR Away Day 2011

Pattern Matching (I)

area (Circle rad) = pi * rad ^ 2area (Rect width height) = width * height

first (Pair value _) = value

Page 16: Functional Programming and Haskell - TWBR Away Day 2011

High Order Functions

Functions which at least:

• Receive functions as parameters

• Return functions (aka curried functions)

Page 17: Functional Programming and Haskell - TWBR Away Day 2011

High Order Functions (I)

map :: (a -> b) -> [a] -> [b]map f [] = []map f (x:xs) = f x : map f xs

Page 18: Functional Programming and Haskell - TWBR Away Day 2011

Currification

add :: Int -> Int -> Intadd x y = x + y

inc :: Int -> Intinc = add 1

Page 19: Functional Programming and Haskell - TWBR Away Day 2011

Lazyness

• aka “call by need”

• Expressions can be evaluated when necessary

• Allows the use of infinite lists

Being pure helps here

Page 20: Functional Programming and Haskell - TWBR Away Day 2011

Lazyness (I)

Definition:even_numbers :: [Int]even_numbers = filter even [1..]

Application:take 5 even_numbers

Page 21: Functional Programming and Haskell - TWBR Away Day 2011

Lazyness (II)

fibs :: [Int]fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

From: http://en.wikipedia.org/wiki/Lazy_evaluation

Page 22: Functional Programming and Haskell - TWBR Away Day 2011

Type Classes

• Created to solve the problem with numeric operator overload and equality testing

• Some type classes defined by Haskell 98:

• Eq

• Read/Show

Page 23: Functional Programming and Haskell - TWBR Away Day 2011

Type Classes (I)

class Eq a where(==), (/=) :: a -> a -> Boolx == y = not (x /= y)x /= y = not (x == y)

You can define what is called a “minimal implementation”.

Page 24: Functional Programming and Haskell - TWBR Away Day 2011

Type Classes (II)data User = User { name :: String }

instance Eq User whereuser1 == user2 = name user1 == name user2

instance Show User whereshow user = name user

Page 25: Functional Programming and Haskell - TWBR Away Day 2011

Automatic Derivation

data Season = Summer | Winter | Autumn | Springderiving (Show, Eq)

show Summer> “Summer”

Summer /= Winter> True

Page 26: Functional Programming and Haskell - TWBR Away Day 2011

Monads

• Adds to the type system a way to describe actions

• The actions will happen in a certain order

Page 27: Functional Programming and Haskell - TWBR Away Day 2011

Monads

• Common monads:

• IO

• State

• Reader

• Maybe

Page 28: Functional Programming and Haskell - TWBR Away Day 2011

Monads

thing1 >>= \x ->func1 x >>= \y ->

thing2 >>= \_ ->func2 y >>= \z ->

return z

do x <- thing1 y <- func1 x thing2 z <- func2 y return z

sugar no-sugar

Page 29: Functional Programming and Haskell - TWBR Away Day 2011

Monads

class Monad m where (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b return :: a -> m a

“return” is a bad name, it actually injects a value into the monadic type.

Page 30: Functional Programming and Haskell - TWBR Away Day 2011

Logger Monadtype Log = [String]

data Logger resultType = Logger (resultType, Log) deriving Show

record x = Logger ((), [x])

instance Monad Logger where return value = Logger (value, []) prevLogger >>= nextAction = let Logger (prevResult, prevLog) = prevLogger Logger (newResult, newLog) = nextAction prevResult in Logger (newResult, prevLog ++ newLog)

Page 31: Functional Programming and Haskell - TWBR Away Day 2011

Testing?

• Go read about QuickCheck!

Page 32: Functional Programming and Haskell - TWBR Away Day 2011

Want to learn more?

Freely available online:http://book.realworldhaskell.org/

Page 33: Functional Programming and Haskell - TWBR Away Day 2011

Your Knowledge Portfolio

"Learn at least one new language every year. [...] Different languages solve the same problems in different ways. By learning several different approaches, you can help broaden your thinking and avoid getting stuck in a rut."

The Pragmatic Programmer

Page 34: Functional Programming and Haskell - TWBR Away Day 2011

Functional Programming with Haskell

Adriano [email protected]

@tanob