1 of 19

Purely Functional Languages

Racket vs. Haskell

2 of 19

What do we mean by "functional"?

Think Scheme and λ-calculus

Everything is a function

A programming paradigm

Recursion and higher-order functions

3 of 19

What do we mean by "pure"?

A pure function has no side-effects

If we call a pure function with the same arguments, we get the same result back every time

Usually what we mean when we talk about a mathematical function [f(x) = x2]

4 of 19

Some examples

(define (add-one x)(+ 1 x))

5 of 19

Some examples

(define (make-incrementor x)(lambda (num) (+ num x))

6 of 19

Some examples

; Returns a random number uniformly; distributed between a and b(define (uniform a b)(+ a � (* (random) (- b a))))

7 of 19

Some examples

(require racket/file)��; returns true if there are more than ; max-lines in the given file(define (too-big? file-path max-lines)(< max-lines� (length (file->lines file-path))))

8 of 19

Some examples

(define speed 10)��(define (distance time)(* time speed))

9 of 19

Some examples

(print (distance 10)) ; 100(set! speed 5)(print (distance 10)) ; 50

10 of 19

What does this mean?

Clearly, Racket is not a purely functional language.

Haskell is a purely functional language:

factorial 0 = 1�factorial n = n * factorial (n - 1)

11 of 19

Referential transparency

Haskell has referential transparency.

x = func 35

Anywhere we see func 35 we can replace it with x

12 of 19

The Good

No side-effects! (strictly enforced)

Optimizations!

Infinite lists and other lazy data structures!

Parallelization! (potentially)

13 of 19

The Bad Interesting

Lazy evaluation

Make new lists/data structures instead of modifying old ones*

* Scheme already does this

14 of 19

The Ugly

Any significant program can't avoid the outside world (state):

  • Writing/reading files
  • User input
  • Networking

Same inputs to same outputs is very restrictive.

15 of 19

... or is it?

Solution: put the state of the world in a box.

We then chain pure functions together that work on data inside of the box.

All the evils of state and the mutable world are contained (no non-pure functions needed).

16 of 19

Monads

Monads are a convenient abstraction to represent this "world in a box" strategy.

17 of 19

Example

The IO monad in Haskell with do syntactic sugar:

copyFile input output = do

contents <- readFile input

writeFile output contents

18 of 19

Let's de-sugar that

copyFile :: String -> String -> IO ()

copyFile input output =

readFile input >>= (\contents ->

writeFile output contents)

19 of 19

What's a monad exactly?

class Monad m where

return :: a -> m a

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