(Today's lecture is not on the midterm)

Size: px
Start display at page:

Download "(Today's lecture is not on the midterm)"

Transcription

1 Midterm on Wednesday of this week in class 3-4:20pm Tenta=ve loca=on: Friend 101 (we are s.ll checking... will no.fy on Piazza... will direct you on the day) Topics: Possibly revisi.ng ques.ons similar to midterm 1 (eg: equa.onal reasoning) Anything in lecture or assigned reading beginning with modules (eg: modules, functors, reasoning about modules, laziness, concurrency) Material oriented around assignments 5 and 6 (Today's lecture is not on the midterm)

2 A Digression: Introducing Haskell COS 326 David Walker Princeton University

3 Haskell Another cool, typed, func.onal programming language Like OCaml in that: it is a func.onal language with parametric polymorphism Unlike OCaml in that it is: pure: func.ons with type a - > b have no effect! lazy: f e does not evaluate e right away; passes e to f has a weak module system; uses type classes has a very sophis.cated type system with higher kinds has several cool extensions for concurrent and parallel programming including transac.onal memory

4 HASKELL BASICS

5 Haskell Defini.ons Mostly like OCaml, with a few small syntac.c differences parameters are immutable by default let declara.ons introduce new func.ons and value foo z = let triple x = x*3 in triple z equivalently, we might use a "where" defini.on: foo z = triple z where triple x = x*3

6 Haskell Indenta.on Haskell, like Python, but unlike Java, OCaml or math wri`en in a notebook, has seman.cally meaningful indenta.on Wrong: must indent func.on body copies k n = if n == 0 then [] else k : copies k (n- 1) indent y =... zap z = let x = z y = z + z in x + y indent z + z zap z = let x = z y = z + z in x + y

7 Haskell Indenta.on Haskell, like Python, but unlike Java, OCaml or math wri`en in a notebook, has seman.cally meaningful indenta.on Right: beginning of x defines indenta.on level copies k n = if n == 0 then [] else k : copies k (n- 1) zap z = let x = z y = z + z in x + y zap z = let x = z y = z + z in x + y

8 Haskell Types We have the op.on of declaring the type of a defini.on prior to the defini.on itself zap :: Int - > Int zap z = let x = z y = z + z in x + y just to be annoying, Haskell uses "::" for "has type" and uses ":" for "cons" the opposite of OCaml

9 Tuples Haskell uses tuples like OCaml constructed by enclosing a sequence of values in parens: ( b, 4) :: (Char, Integer) deconstructed (used) via pa`ern matching: easytoo :: (Integer, Integer, Integer) - > Integer easytoo (x, y, z) = x + y * z

10 Lists Lists are very similar to OCaml lists but the type is wri`en [t] instead of "t list" [1, 2, 3] :: [Integer] [ a, b, c ] :: [Char] [ ] is the empty list (called nil) 1:2:[] is a list with 2 elements String is a synonym for [Char] We can build lists of lists: [ [1, 2], [3], [8, 9, 10] ] :: [ [ Integer ] ]

11 Func.ons over lists - - Sum the elements of a list listsum :: [ Integer ] - > Integer listsum [ ] = 0 listsum (x:xs) = x + listsum xs common to write func.ons using mul.ple clauses, where each clause matches on a different case

12 Func.ons deconstruc.ng lists - - Sum the elements of a list listsum :: [ Integer ] - > Integer lower case le`er = any type at all (a type variable) length :: [a] - > Int listsum [ ] = 0 listsum (x:xs) = x + listsum xs upper case le`er = a concrete type length [ ] = 0 length (x:xs) = 1 + length xs

13 Func.ons deconstruc.ng lists - - Sum the elements of a list listsum :: [ Integer ] - > Integer listsum [ ] = 0 listsum (x:xs) = x + listsum xs cat :: [a] - > [a] - > [a] length :: [a] - > Int length [ ] = 0 length (x:xs) = 1 + length xs cat [ ] xs2 = xs2 cat (x:xs) xs2 = x:(cat xs xs2)

14 Func.ons deconstruc.ng lists - - Sum the elements of a list listsum :: [ Integer ] - > Integer listsum [ ] = 0 listsum (x:xs) = x + listsum xs cat :: [a] - > [a] - > [a] length :: [a] - > Int length [ ] = 0 length (x:xs) = 1 + length xs cat [ ] xs2 = xs2 cat (x:xs) xs2 = x:(cat xs xs2) (++) :: [a] - > [a] - > [a] (++) [ ] xs2 = xs2 (++) (x:xs) xs2 = x:(xs ++ xs2)

15 PURITY & SUBSTITUTION OF EQUALS FOR EQUALS

16 Subs.tu.on of Equals for Equals A key law about Haskell programs: let x = <exp> in... x... x... =... <exp>... <exp>... For example: let x = 4 `div` 2 in x x = (4 `div` 2) (4 `div` 2) = 9

17 Subs.tu.on of Equals for Equals We'd also like to use func.onal abstrac.on without penalty halve :: Int - > Int halve n = n `div` 2 And instead of telling clients about all implementa.on details, simply expose key laws: Lemma 1: for all n, if n is even then (halve n + halve n) = n Now we can reason locally within the client: let x = halve 4 in x + x = = = = (halve 4) (halve 4) (halve 4) + (halve 4) (subs.tu.on) (arithme.c) (Lemma 1) (arithme.c)

18 Computa.onal Effects What happens when we add mutable data structures? Consider this OCaml program: let x = ref 0 let foo (y:int) : int = x :=!x + 1; arg +!x; foo : int - > int We lose a lot of reasoning power! let y = foo 3 in y + y foo 3 + foo 3

19 Computa.onal Effects What happens when we add mutable data structures? Consider this OCaml program: let x = ref 0 let foo (y:int) : int = x :=!x + 1; arg +!x; foo : int - > int We lose a lot of reasoning power! let y = foo 3 in y + y foo 3 + foo 3 8 9

20 Computa.onal Effects What happens when we add mutable data structures? Consider this OCaml program: foo : int - > int let foo (y:int) : int = print_int y; arg +!x; We lose a lot of reasoning power! let y = foo 3 in y + y foo 3 + foo 3 6 prin.ng "3" 6 prin.ng "33"

21 Computa.onal Effects A func.on has an effect if its behavior cannot be specified exclusively as a rela.on between its input and its output I/O is an effect An impera.ve update of a data structure is an effect When func.ons can no longer be described exclusively in terms of the rela.onship between arguments and results many, many fewer equa.onal laws hold In general, in OCaml, let x = <exp> in... x... x <exp>... <exp>... In general, in Haskell, let x = <exp> in... x... x... =... <exp>... <exp>...

22 HASKELL EFFECTS INPUT AND OUTPUT

23 I/O in Haskell Haskell has a special kind of value called an ac.on that describes an effect on the world Pure ac.ons, which just do something and have no interes.ng result are values of type IO () Eg: putstr takes a string and yields an ac.on describing the act of displaying this string on stdout - - writes string to stdout putstr :: String - > IO () - - writes string to stdout followed by newline putstrln :: String - > IO ()

24 I/O in Haskell When do ac.ons actually happen? Ac.ons happen under two circumstances:* 1. the ac.on defined by main happens when your program is executed ie: you compile your program using ghc; then you execute the resul.ng binary 2. the ac.on defined by any expression happens when that expression is wri`en at the ghci prompt * there is one other circumstance: Haskell contains some special, unsafe func.ons that will perform I/O, most notably System.IO.Unsafe.unsafePerformIO so I lied when earlier when I said the equa.on holds in general for Haskell programs...

25 I/O in Haskell hello.hs: main :: IO () main = putstrln Hello world in my shell: dpw@schenn ~/cos441/code/trial $ ghc hello.hs [1 of 1] Compiling Main ( hello.hs, hello.o ) Linking hello.exe... dpw@schenn ~/cos441/code/trial $./hello.exe hello world!

26 bar.hs: bar :: Int - > IO () bar n = putstrln (show n ++ is a super number ) main :: IO () main = bar 6 in my shell: dpw@schenn ~/cos441/code/trial $ ghcii.sh GHCi, version 7.0.3: h`p:// :? for help Loading package ghc- prim... linking... done. Loading package integer- gmp... linking... done. Loading package base... linking... done. Loading package ffi linking... done. Prelude> :l bar [1 of 1] Compiling Main ( bar.hs, interpreted ) Ok, modules loaded: Main. *Main> bar is a super number *Main> main 6 is a super number *Main>

27 Ac.ons Ac.ons are descrip.ons of effects on the world. Simply wri.ng an ac.on does not, by itself cause anything to happen bar.hs: hellos :: [IO ()] hellos = [putstrln Hi, putstrln Hey, putstrln Top of the morning to you ] main = hellos!! 2 in my shell: Prelude> :l hellos... *Main> main Top of the morning to you *Main>

28 Ac.ons Ac.ons are just like any other value - - we can store them, pass them to func.ons, rearrange them, etc: sequence_ :: [IO ()] - > IO () baz.hs: hellos :: [IO ()] hellos = [putstrln Hi, putstrln Hey, putstrln Top of the morning to you ] main = sequence_ (reverse hellos) in my shell: Prelude> :l hellos... *Main> main Top of the morning to you Hey HI

29 Combining Ac.ons The infix operator >> takes two ac.ons a and b and yields an ac.on that describes the effect of execu.ng a then execu.ng b a erward howdy :: IO () howdy = putstr how >> putstrln dy To combine many ac.ons, use do nota.on: bonjour :: IO () bonjour = do putstr Bonjour! putstr putstrln Comment ca va?

30 Quick Aside: Back to SEQEQ* Do we s.ll have it? Yes! let a = PutStrLn "hello" in do a a = do PutStrLn "hello" PutStrLn "hello" an ac.on made up of doing a and then doing a again where a is the PutStrLn "hello" ac.on an ac.on made up of doing the PutStrLn "hello" ac.on and then doing the PutStrLn "hello" ac.on again * SEQEQ = subs.tu.on of equals for equals

31 Input Ac.ons Some ac.ons have an effect and yield a result: - - get a line of input getline :: IO String - - get all of standard input un.l end- of- file encountered getcontents :: IO String - - get command line argument list getargs :: IO [String] What can we do with these kinds of ac.ons? we can extract the value and sequence the effect with another:

32 Input Ac.ons Some ac.ons have an effect and yield a result: - - get a line of input getline :: IO String - - get all of standard input un.l end- of- file encountered getcontents :: IO String - - get command line argument list getargs :: IO [String] What can we do with these kinds of ac.ons? we can extract the value and sequence the effect with another: do s <- getline putstrln s

33 Input Ac.ons Some ac.ons have an effect and yield a result: - - get a line of input getline :: IO String - - get all of standard input un.l end- of- file encountered getcontents :: IO String - - get command line argument list getargs :: IO [String] What can we do with these kinds of ac.ons? we can extract the value and sequence the effect with another: s has type string do s <- getline putstrln s getline has type IO string

34 Input Ac.ons Some ac.ons have an effect and yield a result: - - get a line of input getline :: IO String - - get all of standard input un.l Think end- of- file of type encountered IO String getcontents :: IO String as a box containing a computa.on that will - - get command line argument do list some work and then The "do" packages getargs up :: the IO [String] produce a string. getline getline and the putstrln is such a box. the <- gets s ac.ons up in to a bigger What can we do with s these kinds the of String ac.ons? out of the box composite box we can extract the value and sequence the effect with another: do s <- getline putstrln s

35 A whole program: Input Ac.ons main :: IO () main = do putstrln What s your name? s <- getline putstr Hey, putstr s putstrln, cool name!

36 import modules import System.IO import System.Environment processargs :: [String] - > String processargs [a] = a processargs _ = "" echo :: String - > IO () echo "" = putstrln "Bad Args!" echo filename = do s <- readfile filename putstrln "Here it is:" putstrln "***********" putstr s putstrln "\n***********" main :: IO () main = do args <- getargs let filename = processargs args echo filename contains readfile contains getargs, getprogname <- nota.on: RHS has type IO T LHS has type T let nota.on: RHS has type T LHS has type T

37 SEQEQ (Again!) Recall: s1 ++ s2 concatenates String s1 with String s2 A valid reasoning step: let s = "hello" in do putstrln (s ++ s) = do putstrln ("hello" ++ "hello")

38 SEQEQ (Again!) Recall: s1 ++ s2 concatenates String s1 with String s2 A valid reasoning step: let s = "hello" in do putstrln (s ++ s) = do putstrln ("hello" ++ "hello") A valid reasoning step: do let s = "hello" putstrln (s ++ s) = do putstrln ("hello" ++ "hello")

39 SEQEQ (Again!) Recall: s1 ++ s2 concatenates String s1 with String s2 A valid reasoning step: let s = "hello" in do putstrln (s ++ s) = do putstrln ("hello" ++ "hello") A valid reasoning step: do let s = "hello" putstrln (s ++ s) Wait, what about this: do s <- getline putstrln (s ++ s) = do putstrln ("hello" ++ "hello") wrong type: getline :: IO String do putstrln (getline ++ getline)

40 Invalid reasoning step? SEQEQ (Again!) let s = getline in do putstrln (s ++ s)? = do putstrln (getline ++ getline)

41 Invalid reasoning step? SEQEQ (Again!) let s = getline in do putstrln (s ++ s)? = do putstrln (getline ++ getline) wrong type: s :: IO String wrong type: getline :: IO String

42 Invalid reasoning step? SEQEQ (Again!) let s = getline in do putstrln (s ++ s)? = do putstrln (getline ++ getline) wrong type: s :: IO String wrong type: getline :: IO String The Haskell type system shows x <- e is different from let x = e x has a different type in each case let x = e enables subs.tu.on of e for x in what follows x <- e does not enable subs.tu.on - - a`emp.ng subs.tu.on leaves you with code that won't even type check because x and e have different types (type T vs. type IO T)

43 HASKELL EFFECTS: REFERENCES

44 Coming Back to References Again Remember this OCaml func.on: let x = ref 0 foo : int - > int We no.ced that: let foo (y:int) : int = x :=!x + 1; arg +!x; let y = foo 3 in y + y foo 3 + foo 3 What if we write something similar in Haskell? : int

45 Coming Back to References Again Remember this OCaml func.on: let x = ref 0 foo : int - > int We no.ced that: let foo (y:int) : int = x :=!x + 1; arg +!x; let y = foo 3 in y + y foo 3 + foo 3 What if we write something similar in Haskell? x :: Ref int foo :: int - > int foo y = x := read x + 1; arg +!x; doesn't type check : int

46 Haskell Types Tell You Where the Effects Aren't! Haskell func3on types are pure - - totally effect- free foo : int -> int Haskell s type system forces* purity on func.ons with type a -> b no prin.ng no mutable data no reading from files no concurrency no benign effects (like memoiza.on) * except for unsafeperformio exp : int Same with expressions. Expressions with just type int have no effect!

47 Haskell Types Tell You Where the Effects Aren't! foo :: int -> int totally pure func3on <code> :: IO int suspended (lazy) computa3on that performs effects when executed

48 Haskell Types Tell You Where the Effects Aren't! foo :: int -> int totally pure func3on <code> :: IO int suspended (lazy) computa3on that performs effects when executed bar :: int -> IO int totally pure func3on that returns suspended ac3on

49 Haskell Types Tell You Where the Effects Aren't! print :: string -> IO () reverse :: string -> string reverse hello :: string print (reverse hello ) :: IO () the type system always tells you when an effect has happened effects can t escape the I/O monad

50 References read :: Ref a -> IO a (+) :: int -> int -> int r :: Ref int (read r) + 3 :: int Doesn t type check

51 References read :: Ref a -> IO a (+) :: int -> int -> int r :: Ref int do x <- read r return (x + 3) the "return" ac.on has no effect; it just returns its value creates a composi.on ac.on that reads a references and produces the value in that reference plus 3

52 Mutable State new :: a -> IO (Ref a) read :: Ref a -> IO a write :: Ref a -> a -> IO () Haskell uses new, read, and write* func.ons within the IO Monad to manage mutable state. main = do r <- new 0; -- let r = ref 0 in inc r; -- r :=!r+1; s <- read r; -- s :=!r; print s inc :: Ref Int -> IO () inc r = do v <- read r; -- v :=!r write r (v+1) -- r :=!v +1 * actually newref, readref, writeref,

53 MONADS

54 The Bigger Picture Haskell's type system (at least the part of it that we have seen so far) is very similar to the ML type system eg: typing rules for pure primi.ves (func.ons, pairs, lists, etc) are similar in both cases: if f : t1 - > t2 and e : t1 then (f e) : t2 if e1 : t1 and e2 : t2 then (e1, e2) : (t1, t2) What Haskell has done that is special is: it has been very careful to give effec ul primi.ves special types involving "IO t" it has a func.ons to compose ac.ons with type "IO t" the IO data type + its composi.on func.ons are called a monad it has special syntax for programming with monads

55 We can talk about what monads are by referring to their interface Recall an interface declares some new abstract types and some opera.ons over values with those abstract types. For example: module type CONTAINER = sig type a t (* the type of the container *) There are lots of different implementations of such containers: queues, stacks, sets, randomized sets,... val empty : a t val insert : a -> a t -> a t val remove : a t -> a option * a t val fold : ( a -> b -> b) -> b -> a t -> b end

56 We can talk about what monads are by referring to their interface Recall an interface declares some new abstract types and some opera.ons over values with those abstract types. For example: module type CONTAINER = sig type a t (* the type of the container *) val empty : a t val insert : a -> a t -> a t val remove : a t -> a option * a t val fold : ( a -> b -> b) -> b -> a t -> b end There are lots of different implementations of such containers: queues, stacks, sets, randomized sets,... Interfaces can come with some equations one expects every implementation to satisfy. eg: fold f base empty == base The equations specify some, but not all of the behavior of the module (eg: stacks and queues remove elements in different orders)

57 Monads A monad is just a par.cular interface. Two views: (1) interface for a very generic container, with opera.ons designed to support composi3on of computa.ons over the contents of containers (2) interface for an abstract computa.on that does some book keeping on the side. Book keeping is code for has an effect. Once again, the support for composi.on is key. since func.onal programmers know that func.ons are data, the two views actually coincide

58 Monads A monad is just a par.cular interface. Two views: (1) interface for a very generic container, with opera.ons designed to support composi3on of computa.ons over the contents of containers (2) interface for an abstract computa.on that does some book keeping on the side. Book keeping is code for has an effect. Once again, the support for composi.on is key. since func.onal programmers know that func.ons are data, the two views actually coincide Many different kinds of monads: monads for handling/accumula.ng errors monads for processing collec.ons en masse monads for logging strings that should be printed monads for coordina.ng concurrent threads (see OCaml Asynch library) monads for back- tracking search monads for transac3onal memory

59 Monads A monad is just a par.cular interface. Two views: (1) interface for a very generic container, with opera.ons designed to support composi3on of computa.ons over the contents of containers (2) interface for an abstract computa.on that does some book keeping on the side. Book keeping is code for has an effect. Once again, the support for composi.on is key. since func.onal programmers know that func.ons are data, the two views actually coincide Many different kinds of monads: monads for handling/accumula.ng errors monads for processing collec.ons en masse monads for logging strings that should be printed monads for coordina.ng concurrent threads (see OCaml Asynch library) monads for back- tracking search monads for transac3onal memory Because a monad is just a par.cular interface (with many useful implementa.ons), you can implement monads in any language But, Haskell is famous for them because it has a special built- in syntax that makes monads par.cularly easy and elegant to use F#, Scala have adopted similar syntac.c ideas Monads also play a very special role in the overall design of the Haskell language

60 What is the monad interface? module type MONAD = sig type a M val return : a -> a M val (>>=) : a M -> ( a -> b M) -> b M + some equations specifying how return and bind are required to interact end Consider first the container interpretation : a M is a container for values with type a return x puts x in the container bind c f takes the values in c out of the container and applies f to them, forming a new container holding the results - bind c f is often written as: c >>= f

61 The Op.ons as a Container module type MONAD = sig type a M val return : a -> a M val (>>=) : a M -> ( a -> b M) -> b M end module OptionMonad = struct type a M = a option let return x = Some x let (>>=) c f = match c with None -> None Some v -> f v end put value in a container take value v out of a container c and then apply f, producing a new container

62 The Op.ons as a Container module type MONAD = sig type a M val return : a -> a M val (>>=) : a M -> ( a -> b M) -> b M end using the option container: type file_name = string val read_file : file_name -> string M let concat f1 f2 = readfile f1 >>= (fun contents1 -> readfile f2 >>= (fun contents2 -> return (contents1 ^ contents2) ;; module OptionMonad = struct type a M = a option let return x = Some x let (>>=) c f = match c with None -> None Some v -> f v end put value in a container take value v out of a container c and then apply f, producing a new container

63 Book- keeping Interpreta.on: The Op.on Monad as Possibly Erroneous Computa.on module type MONAD = sig type a M val return : a -> a M val (>>=) : a M -> ( a -> b M) -> b M end using the error monad: type file_name = string module ErrorMonad = struct type a M = a option let return x = Some x let (>>=) c f = match c with None -> None Some v -> f v end val read_file : file_name -> string M let concat f1 f2 = readfile f1 >>= (fun contents1 -> readfile f2 >>= (fun contents2 -> return (contents1 ^ contents2) ;; compose book-keeping: check to see if error has occurred, if so return None, else continue setting up book keeping for error processing

64 Lists as Containers module type MONAD = sig type a M val return : a -> a M val (>>=) : a M -> ( a -> b M) -> b M end module ListMonad = struct type a M = a list let return x = [x] let (>>=) c f = List.flatten (List.map f c) using the list monad: random_sample : unit -> int M monte_carlo : int -> int -> int -> result let experiments : result M = random_sample() >>= (fun s1 -> random_sample() >>= (fun s2 -> random_sample() >>= (fun s3 -> return (monte_carlo s1 s2 s3) ;; end apply f to all elements of the list c, creating a list of lists and then flatten results in to single list put element in to list container

65 The List Monad as Nondeterminis.c Computa.on module type MONAD = sig type a M val return : a -> a M val (>>=) : a M -> ( a -> b M) -> b M end using the non-determinism monad: random_sample : unit -> int M monte_carlo : int -> int -> int -> result let experiments : result M = random_sample() >>= (fun s1 -> random_sample() >>= (fun s2 -> random_sample() >>= (fun s3 -> return (monte_carlo s1 s2 s3) ;; module ListMonad = struct type a M = a list let return x = [x] let (>>=) c f = List.flatten (List.map f c) end one result; compose many no non-determinism possible results (c) with a non-deterministic continuation f

66 A Container with a String on the Side (aka: A logging/prin.ng monad) module type MONAD = sig type a M val return : a -> a M val (>>=) : a M -> ( a -> b M) -> b M end using the logging monad: record : ( a -> b) -> a -> string -> b M module LoggingMonad = struct type a M = a * string let return x = (x, ) let (>>=) c f = let (v, s) = c in let (v,s ) = f v in (v, s ^ s ) end let record f x s = (f x, s) let do x = record read x read it >>= (fun v -> record write v wrote it >>= (fun _ -> record write v wrote it again >>= (fun _ -> return v ;; concatenate the log of c with the log produced by running f nothing logged yet

67 A Container with a State on the Side (aka: A logging/prin.ng monad) module type MONAD = sig type a M val return : a -> a M val (>>=) : a M -> ( a -> b M) -> b M end module StateMonad = struct type state = address int map type a M = a * (state -> state) let return x =??? let (>>=) c f =??? let read a =??? let write a v =??? end

68 Monad Laws Just like one expects any CONTAINER to behave in a par.cular way, one has expecta.ons of MONADs. Le iden.ty: return does nothing observable (1) return v >>= f == f v Right iden.ty: return s.ll doesn t do anything observable (2) m >>= return == m Associa.vity: composing m with f first and then doing g is the same as doing m with the composi.on of f and g (3) (m >>= f) >>= g == m >>= (fun x - > f x >>= g)

69 Breaking the Law Just like one expects any CONTAINER to behave in a par.cular way, one has expecta.ons of MONADs. Le iden.ty: return does nothing observable (1) return v >>= f == f v module LoggingMonad = struct type a M = a * string return 3 >>= fun x -> return x == (3, start ) >>= fun x -> return x == (3, start ^ start ) == (3, startstart ) let return x = (x, start ) let (>>=) c f = let (v, s) = c in let (v,s ) = f v in (v, s ^ s ) end (fun x -> return x) 3 == return 3 == (3, start )

70 Breaking the Law What are the consequences of breaking the law? Well, if you told your friend you ve implemented a monad and they can use it in your code, they will expect that they can rewrite their code using equa.ons like this one: return x >>= f == f x If you tell your friend you ve implemented the monad interface but none of the monad laws hold your friend will probably say: Ok, tell me what your func.ons do then and please stop using the word monad because it is confusing. It is like you are claiming to have implemented the QUEUE interface but insert and remove are First- In, First- Out like a stack. In Haskell or Fsharp or Scala, breaking the monad laws may have more severe consequences, because the compiler actually uses those laws to do some transforma.ons of your code.

71 HASKELL WRAPUP

72 A Monadic Skin In languages like ML or Java, there is no way to dis.nguish between: pure func.ons with type int - > int effec ul func.ons with type int - > int In Haskell, the programmer can choose when to live in the IO monad and when to live in the realm of pure func.onal programming. Counter- point: We have shown that it is useful to be able to build pure abstrac.ons using impera.ve infrastructure (eg: laziness, futures, parallel sequences, memoiza.on). You can t do that in Haskell (without escaping the type system via unsafei0) Interes.ng perspec.ve: It is not Haskell that lacks impera.ve features, but rather the other languages that lack the ability to have a sta.cally dis.nguishable pure subset. At any rate, a checked pure- impure separa.on facilitates concurrent programming.

73 The Central Challenge Useful Arbitrary effects Useless No effects Dangerous Safe

74 The Challenge of Effects Plan A (everyone else) Useful Arbitrary effects Nirvana Plan B (Haskell) Useless Dangerous No effects Safe

75 Two Basic Approaches: Plan A Arbitrary effects Examples Regions Ownership types Vault, Spec#, Cyclone Default = Any effect Plan = Add restrictions

76 Two Basic Approaches: Plan B Default = No effects Plan = Selectively permit effects Types play a major role Two main approaches: Domain specific languages (SQL, Xquery, Google map/ reduce) Wide- spectrum func.onal languages + controlled effects (e.g. Haskell) Value oriented programming

77 Lots of Cross Over Useful Arbitrary effects Plan A (everyone else) Nirvana Useless Dangerous according to Simon Peyton Jones, inventor of Haskell :- ) Envy No effects Safe Plan B (Haskell)

78 Lots of Cross Over Useful Arbitrary effects Plan A (everyone else) Nirvana Ideas; e.g. Software Transactional Memory Plan B (Haskell) Useless Dangerous No effects Safe

79 An Assessment and a Predic.on One of Haskell s most significant contributions is to take purity seriously, and relentlessly pursue Plan B. Imperative languages will embody growing (and checkable) pure subsets. -- Simon Peyton Jones

Haskell a lazy, purely func1onal language

Haskell a lazy, purely func1onal language Haskell a lazy, purely func1onal language COS 326 David Walker Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel permission granted to reuse these slides for non-commercial

More information

Haskell. COS 326 Andrew W. Appel Princeton University. a lazy, purely functional language. slides copyright David Walker and Andrew W.

Haskell. COS 326 Andrew W. Appel Princeton University. a lazy, purely functional language. slides copyright David Walker and Andrew W. Haskell a lazy, purely functional language COS 326 Andrew W. Appel Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel Haskell Another cool, typed, functional programming language

More information

David Walker. Thanks to Kathleen Fisher and recursively to Simon Peyton Jones for much of the content of these slides.

David Walker. Thanks to Kathleen Fisher and recursively to Simon Peyton Jones for much of the content of these slides. David Walker Thanks to Kathleen Fisher and recursively to Simon Peyton Jones for much of the content of these slides. Optional Reading: Beautiful Concurrency, The Transactional Memory / Garbage Collection

More information

COS 326 David Walker. Thanks to Kathleen Fisher and recursively to Simon Peyton Jones for much of the content of these slides.

COS 326 David Walker. Thanks to Kathleen Fisher and recursively to Simon Peyton Jones for much of the content of these slides. COS 326 David Walker Thanks to Kathleen Fisher and recursively to Simon Peyton Jones for much of the content of these slides. Optional Reading: Beautiful Concurrency, The Transactional Memory / Garbage

More information

CS 11 Haskell track: lecture 1

CS 11 Haskell track: lecture 1 CS 11 Haskell track: lecture 1 This week: Introduction/motivation/pep talk Basics of Haskell Prerequisite Knowledge of basic functional programming e.g. Scheme, Ocaml, Erlang CS 1, CS 4 "permission of

More information

A Func'onal Introduc'on. COS 326 David Walker Princeton University

A Func'onal Introduc'on. COS 326 David Walker Princeton University A Func'onal Introduc'on COS 326 David Walker Princeton University Thinking Func'onally In Java or C, you get (most) work done by changing something temp = pair.x; pair.x = pair.y; pair.y = temp; commands

More information

Haskell Monads CSC 131. Kim Bruce

Haskell Monads CSC 131. Kim Bruce Haskell Monads CSC 131 Kim Bruce Monads The ontological essence of a monad is its irreducible simplicity. Unlike atoms, monads possess no material or spatial character. They also differ from atoms by their

More information

References. Monadic I/O in Haskell. Digression, continued. Digression: Creating stand-alone Haskell Programs

References. Monadic I/O in Haskell. Digression, continued. Digression: Creating stand-alone Haskell Programs References Monadic I/O in Haskell Jim Royer CIS 352 March 6, 2018 Chapter 18 of Haskell: the Craft of Functional Programming by Simon Thompson, Addison-Wesley, 2011. Chapter 9 of Learn you a Haskell for

More information

Introduction to Haskell

Introduction to Haskell Introduction to Haskell Matt Mullins Texas A&M Computing Society October 6, 2009 Matt Mullins (TACS) Introduction to Haskell October 6, 2009 1 / 39 Outline Introduction to Haskell Functional Programming

More information

Thinking Induc,vely. COS 326 David Walker Princeton University

Thinking Induc,vely. COS 326 David Walker Princeton University Thinking Induc,vely COS 326 David Walker Princeton University slides copyright 2017 David Walker permission granted to reuse these slides for non-commercial educa,onal purposes Administra,on 2 Assignment

More information

Background Type Classes (1B) Young Won Lim 6/28/18

Background Type Classes (1B) Young Won Lim 6/28/18 Background Type Classes (1B) Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2

More information

(Func&onal (Programming (in (Scheme)))) Jianguo Lu

(Func&onal (Programming (in (Scheme)))) Jianguo Lu (Func&onal (Programming (in (Scheme)))) Jianguo Lu 1 Programming paradigms Func&onal No assignment statement No side effect Use recursion Logic OOP AOP 2 What is func&onal programming It is NOT what you

More information

Thinking Induc,vely. COS 326 David Walker Princeton University

Thinking Induc,vely. COS 326 David Walker Princeton University Thinking Induc,vely COS 326 David Walker Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel permission granted to reuse these slides for non-commercial educa,onal purposes

More information

Programming with Math and Logic

Programming with Math and Logic .. Programming with Math and Logic an invitation to functional programming Ed Morehouse Wesleyan University The Plan why fp? terms types interfaces The What and Why of Functional Programming Computing

More information

CS The IO Monad. Slides from John Mitchell, K Fisher, and S. Peyton Jones

CS The IO Monad. Slides from John Mitchell, K Fisher, and S. Peyton Jones CS 242 2012 The IO Monad Slides from John Mitchell, K Fisher, and S. Peyton Jones Reading: Tackling the Awkward Squad, Sections 1-2 Real World Haskell, Chapter 7: I/O Beauty... Functional programming is

More information

I/O in Purely Functional Languages. Stream-Based I/O. Continuation-Based I/O. Monads

I/O in Purely Functional Languages. Stream-Based I/O. Continuation-Based I/O. Monads I/O in Purely Functional Languages Stream-Based I/O Four centuries ago, Descartes pondered the mind-body problem: how can incorporeal minds interact with physical bodies? Designers of purely declarative

More information

CS153: Compilers Lecture 15: Local Optimization

CS153: Compilers Lecture 15: Local Optimization CS153: Compilers Lecture 15: Local Optimization Stephen Chong https://www.seas.harvard.edu/courses/cs153 Announcements Project 4 out Due Thursday Oct 25 (2 days) Project 5 out Due Tuesday Nov 13 (21 days)

More information

Informatics 1 Functional Programming 19 Tuesday 23 November IO and Monads. Philip Wadler University of Edinburgh

Informatics 1 Functional Programming 19 Tuesday 23 November IO and Monads. Philip Wadler University of Edinburgh Informatics 1 Functional Programming 19 Tuesday 23 November 2010 IO and Monads Philip Wadler University of Edinburgh The 2010 Informatics 1 Competition Sponsored by Galois (galois.com) List everyone who

More information

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013 CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Winter 2013 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

More information

CS457/557 Functional Languages

CS457/557 Functional Languages CS457/557 Functional Languages Spring 2018 Lecture 1: Course Introduction Andrew Tolmach Portland State University (with thanks to Mark P. Jones) 1 Goals of this course Introduce the beautiful ideas of

More information

Muta%on. COS 326 David Walker Princeton University

Muta%on. COS 326 David Walker Princeton University Muta%on COS 326 David Walker Princeton University slides copyright 2017 David Walker permission granted to reuse these slides for non-commercial educa%onal purposes Reasoning about Mutable State is Hard

More information

Side Effects (3B) Young Won Lim 11/20/17

Side Effects (3B) Young Won Lim 11/20/17 Side Effects (3B) Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later

More information

Haskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder

Haskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder Outline 1 2 3 4 What is Haskell? Haskell is a functional programming language. Characteristics functional non-strict ( lazy ) pure (no side effects*) strongly statically typed available compiled and interpreted

More information

Monad Background (3A) Young Won Lim 11/18/17

Monad Background (3A) Young Won Lim 11/18/17 Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

More information

Monad Background (3A) Young Won Lim 11/8/17

Monad Background (3A) Young Won Lim 11/8/17 Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

More information

Mutation. COS 326 David Walker Princeton University

Mutation. COS 326 David Walker Princeton University Mutation COS 326 David Walker Princeton University Mutation? 2 Thus far We have considered the (almost) purely functional subset of Ocaml. We ve had a few side effects: printing & raising exceptions. Two

More information

Side Effects (3B) Young Won Lim 11/23/17

Side Effects (3B) Young Won Lim 11/23/17 Side Effects (3B) Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later

More information

A Functional Evaluation Model

A Functional Evaluation Model A Functional Evaluation Model COS 326 Andrew W. Appel Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel A Functional Evaluation Model In order to be able to write a program,

More information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation

More information

IO Monad (3D) Young Won Lim 1/18/18

IO Monad (3D) Young Won Lim 1/18/18 Copyright (c) 2016-2018 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

More information

Side Effects (3B) Young Won Lim 11/27/17

Side Effects (3B) Young Won Lim 11/27/17 Side Effects (3B) Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later

More information

CS 360: Programming Languages Lecture 10: Introduction to Haskell

CS 360: Programming Languages Lecture 10: Introduction to Haskell CS 360: Programming Languages Lecture 10: Introduction to Haskell Geoffrey Mainland Drexel University Thursday, February 5, 2015 Adapted from Brent Yorgey s course Introduction to Haskell. Section 1 Administrivia

More information

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

n   n Try tutorial on front page to get started! n   spring13/ n Stack Overflow! Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Haskell Programming

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Haskell Programming About the Tutorial Haskell is a widely used purely functional language. Functional programming is based on mathematical functions. Besides Haskell, some of the other popular languages that follow Functional

More information

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules Haskell: From Basic to Advanced Part 2 Type Classes, Laziness, IO, Modules Qualified types In the types schemes we have seen, the type variables were universally quantified, e.g. ++ :: [a] -> [a] -> [a]

More information

IO Monad (3C) Young Won Lim 1/6/18

IO Monad (3C) Young Won Lim 1/6/18 Copyright (c) 2016-2018 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

More information

Introduction to Functional Programming and Haskell. Aden Seaman

Introduction to Functional Programming and Haskell. Aden Seaman Introduction to Functional Programming and Haskell Aden Seaman Functional Programming Functional Programming First Class Functions Expressions (No Assignment) (Ideally) No Side Effects Different Approach

More information

Implemen'ng OCaml in OCaml

Implemen'ng OCaml in OCaml 1 An OCaml defini'on of OCaml evalua'on, or, Implemen'ng OCaml in OCaml COS 326 David Walker Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel permission granted to reuse

More information

The Haskell HOP: Higher-order Programming

The Haskell HOP: Higher-order Programming The Haskell HOP: Higher-order Programming COS 441 Slides 6 Slide content credits: Ranjit Jhala, UCSD Agenda Haskell so far: First-order functions This time: Higher-order functions: Functions as data, arguments

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques () Lecture 13 February 12, 2018 Mutable State & Abstract Stack Machine Chapters 14 &15 Homework 4 Announcements due on February 20. Out this morning Midterm results

More information

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages Harvard School of Engineering and Applied Sciences CS 152: Programming Languages Lecture 18 Thursday, March 29, 2018 In abstract algebra, algebraic structures are defined by a set of elements and operations

More information

Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell

Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell Ori Bar El Maxim Finkel 01/11/17 1 History Haskell is a lazy, committee designed, pure functional programming language that

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages h"p://www.di.unipi.it/~andrea/dida2ca/plp- 14/ Prof. Andrea Corradini Department of Computer Science, Pisa Introduc;on to Hakell Lesson 27! 1 The origins: ML programming

More information

Informatics 1 Functional Programming Lectures 15 and 16. IO and Monads. Don Sannella University of Edinburgh

Informatics 1 Functional Programming Lectures 15 and 16. IO and Monads. Don Sannella University of Edinburgh Informatics 1 Functional Programming Lectures 15 and 16 IO and Monads Don Sannella University of Edinburgh Part I The Mind-Body Problem The Mind-Body Problem Part II Commands Print a character putchar

More information

CS 457/557: Functional Languages

CS 457/557: Functional Languages CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University 1 Why Lists? Lists are a heavily used data structure in many functional programs Special syntax is

More information

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Topics Covered Thus Far CMSC 330: Organization of Programming Languages Topics Covered Thus Far CMSC 330: Organization of Programming Languages Names & Binding, Type Systems Programming languages Ruby Ocaml Lambda calculus Syntax specification Regular expressions Context free

More information

Advanced Programming Handout 7. Monads and Friends (SOE Chapter 18)

Advanced Programming Handout 7. Monads and Friends (SOE Chapter 18) Advanced Programming Handout 7 Monads and Friends (SOE Chapter 18) The Type of a Type In previous chapters we discussed: Monomorphic types such as Int, Bool, etc. Polymorphic types such as [a], Tree a,

More information

Monads. COS 441 Slides 16

Monads. COS 441 Slides 16 Monads COS 441 Slides 16 Last time: Agenda We looked at implementation strategies for languages with errors, with printing and with storage We introduced the concept of a monad, which involves 3 things:

More information

Programming in Haskell Aug Nov 2015

Programming in Haskell Aug Nov 2015 Programming in Haskell Aug Nov 2015 LECTURE 23 NOVEMBER 12, 2015 S P SURESH CHENNAI MATHEMATICAL INSTITUTE Summary of IO Actions of type IO t1, t1 -> IO t2, t1 -> t2 -> IO t3 etc. As opposed to pure functions

More information

Lecture 10: Potpourri: Enum / struct / union Advanced Unix #include function pointers

Lecture 10: Potpourri: Enum / struct / union Advanced Unix #include function pointers ....... \ \ \ / / / / \ \ \ \ / \ / \ \ \ V /,----' / ^ \ \.--..--. / ^ \ `--- ----` / ^ \. ` > < / /_\ \. ` / /_\ \ / /_\ \ `--' \ /. \ `----. / \ \ '--' '--' / \ / \ \ / \ / / \ \ (_ ) \ (_ ) / / \ \

More information

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

More information

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java OCaml Data : Organization of Programming Languages OCaml 4 Data Types & Modules So far, we ve seen the following kinds of data Basic types (int, float, char, string) Lists Ø One kind of data structure

More information

Mutable Data Types. Prof. Clarkson Fall A New Despair Mutability Strikes Back Return of Imperative Programming

Mutable Data Types. Prof. Clarkson Fall A New Despair Mutability Strikes Back Return of Imperative Programming Mutable Data Types A New Despair Mutability Strikes Back Return of Imperative Programming Prof. Clarkson Fall 2017 Today s music: The Imperial March from the soundtrack to Star Wars, Episode V: The Empire

More information

Side Effects (3A) Young Won Lim 1/13/18

Side Effects (3A) Young Won Lim 1/13/18 Side Effects (3A) Copyright (c) 2016-2018 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later

More information

Introduction to OCaml

Introduction to OCaml Fall 2018 Introduction to OCaml Yu Zhang Course web site: http://staff.ustc.edu.cn/~yuzhang/tpl References Learn X in Y Minutes Ocaml Real World OCaml Cornell CS 3110 Spring 2018 Data Structures and Functional

More information

!!"!#"$%& Atomic Blocks! Atomic blocks! 3 primitives: atomically, retry, orelse!

!!!#$%& Atomic Blocks! Atomic blocks! 3 primitives: atomically, retry, orelse! cs242! Kathleen Fisher!! Multi-cores are coming!! - For 50 years, hardware designers delivered 40-50% increases per year in sequential program speed.! - Around 2004, this pattern failed because power and

More information

COSC 111: Computer Programming I. Dr. Bowen Hui University of Bri>sh Columbia Okanagan

COSC 111: Computer Programming I. Dr. Bowen Hui University of Bri>sh Columbia Okanagan COSC 111: Computer Programming I Dr. Bowen Hui University of Bri>sh Columbia Okanagan 1 First half of course SoEware examples From English to Java Template for building small programs Exposure to Java

More information

Programming Paradigms

Programming Paradigms PP 2017/18 Unit 11 Functional Programming with Haskell 1/37 Programming Paradigms Unit 11 Functional Programming with Haskell J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE

More information

More on functional programming

More on functional programming More on functional programming Emphasis on Haskell (as a pure functional language) Input and output in Haskell Wrappers / contexts Monads chaining wrapped computations Maybe and lists as monads Return

More information

Background Type Classes (1B) Young Won Lim 6/14/18

Background Type Classes (1B) Young Won Lim 6/14/18 Background Type Classes (1B) Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2

More information

Lecture 4: Build Systems, Tar, Character Strings

Lecture 4: Build Systems, Tar, Character Strings CIS 330:! / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 4:

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 10 February 5 th, 2016 Abstract types: sets Lecture notes: Chapter 10 What is the value of this expresssion? let f (x:bool) (y:int) : int = if x then

More information

Programming Languages

Programming Languages Programming Languages Andrea Flexeder Chair for Theoretical Computer Science Prof. Seidl TU München winter term 2010/2011 Lecture 10 Side-Effects Main Points you should get: Why monads? What is a monad?

More information

JVM ByteCode Interpreter

JVM ByteCode Interpreter JVM ByteCode Interpreter written in Haskell (In under 1000 Lines of Code) By Louis Jenkins Presentation Schedule ( 15 Minutes) Discuss and Run the Virtual Machine first

More information

IO Monad (3C) Young Won Lim 8/23/17

IO Monad (3C) Young Won Lim 8/23/17 Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

More information

Background. CMSC 330: Organization of Programming Languages. Useful Information on OCaml language. Dialects of ML. ML (Meta Language) Standard ML

Background. CMSC 330: Organization of Programming Languages. Useful Information on OCaml language. Dialects of ML. ML (Meta Language) Standard ML CMSC 330: Organization of Programming Languages Functional Programming with OCaml 1 Background ML (Meta Language) Univ. of Edinburgh, 1973 Part of a theorem proving system LCF The Logic of Computable Functions

More information

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011 CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Fall 2011 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

More information

Background Operators (1E) Young Won Lim 7/7/18

Background Operators (1E) Young Won Lim 7/7/18 Background Operators (1E) Copyright (c) 2016-2018 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2

More information

Lazy Functional Programming in Haskell

Lazy Functional Programming in Haskell Lazy Functional Programming in Haskell David Raymond Christiansen 25 November, 2013 What is Haskell? 2 What is Haskell? Pure functional language: no side effects 2 What is Haskell? Pure functional language:

More information

Monads. Prof. Clarkson Fall Today s music: Vámanos Pal Monte by Eddie Palmieri

Monads. Prof. Clarkson Fall Today s music: Vámanos Pal Monte by Eddie Palmieri Monads Prof. Clarkson Fall 2017 Today s music: Vámanos Pal Monte by Eddie Palmieri Review Currently in 3110: Advanced topics Futures: Async: deferreds, return, bind Today: Monads Monad tutorials since

More information

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program

More information

Lecture 13: Abstract Data Types / Stacks

Lecture 13: Abstract Data Types / Stacks ....... \ \ \ / / / / \ \ \ \ / \ / \ \ \ V /,----' / ^ \ \.--..--. / ^ \ `--- ----` / ^ \. ` > < / /_\ \. ` / /_\ \ / /_\ \ `--' \ /. \ `----. / \ \ '--' '--' / \ / \ \ / \ / / \ \ (_ ) \ (_ ) / / \ \

More information

CSCE 314 Programming Languages. Interactive Programming: I/O

CSCE 314 Programming Languages. Interactive Programming: I/O CSCE 314 Programming Languages Interactive Programming: I/O Dr. Hyunyoung Lee 1 Introduction To date, we have seen how Haskell can be used to write batch programs that take all their inputs at the start

More information

CSC324 Principles of Programming Languages

CSC324 Principles of Programming Languages CSC324 Principles of Programming Languages http://mcs.utm.utoronto.ca/~324 November 14, 2018 Today Final chapter of the course! Types and type systems Haskell s type system Types Terminology Type: set

More information

Applicatives Comparisons (2C) Young Won Lim 3/6/18

Applicatives Comparisons (2C) Young Won Lim 3/6/18 Comparisons (2C) Copyright (c) 2016-2018 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later

More information

Condi(onals and Loops

Condi(onals and Loops Condi(onals and Loops 1 Review Primi(ve Data Types & Variables int, long float, double boolean char String Mathema(cal operators: + - * / % Comparison: < > = == 2 A Founda(on for Programming any program

More information

An introduction introduction to functional functional programming programming using usin Haskell

An introduction introduction to functional functional programming programming using usin Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques () Lecture 20 February 28, 2018 Transition to Java Announcements HW05: GUI programming Due: THURSDAY!! at 11:59:59pm Lots of TA office hours today Thursday See Piazza

More information

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming CMSC 330: Organization of Programming Languages OCaml Imperative Programming CMSC330 Spring 2018 1 So Far, Only Functional Programming We haven t given you any way so far to change something in memory

More information

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016 CSE341: Programming Languages Lecture 11 Type Inference Dan Grossman Spring 2016 Type-checking (Static) type-checking can reject a program before it runs to prevent the possibility of some errors A feature

More information

Futures. COS 326 David Walker Princeton University

Futures. COS 326 David Walker Princeton University Futures COS 326 David Walker Princeton University Futures module type FUTURE = sig type a future (* future f x forks a thread to run f(x) and stores the result in a future when complete *) val future :

More information

Introduction to Functional Programming

Introduction to Functional Programming A Level Computer Science Introduction to Functional Programming William Marsh School of Electronic Engineering and Computer Science Queen Mary University of London Aims and Claims Flavour of Functional

More information

CSE399: Advanced Programming

CSE399: Advanced Programming What is Advanced Programming? Good programmers... CSE399: Advanced Programming Handout 1 write code that gets the job done Excellent programmers... write code that other people can read, understand, maintain,

More information

Haskell An Introduction

Haskell An Introduction Haskell An Introduction What is Haskell? General purpose Purely functional No function can have side-effects IO is done using special types Lazy Strongly typed Polymorphic types Concise and elegant A First

More information

Monads in Haskell. Nathanael Schilling. December 12, 2014

Monads in Haskell. Nathanael Schilling. December 12, 2014 Monads in Haskell Nathanael Schilling December 12, 2014 Abstract In Haskell, monads provide a mechanism for mapping functions of the type a -> m b to those of the type m a -> m b. This mapping is dependent

More information

Monad Background (3A) Young Won Lim 10/5/17

Monad Background (3A) Young Won Lim 10/5/17 Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

More information

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ 10 Stacks of Coins You have 10 stacks with 10 coins each that look and feel

More information

Programming Languages Fall 2013

Programming Languages Fall 2013 Programming Languages Fall 2013 Lecture 2: types Prof. Liang Huang huang@qc.cs.cuny.edu Recap of Lecture 1 functional programming vs. imperative programming basic Haskell syntax function definition lazy

More information

CS 440: Programming Languages and Translators, Spring 2019 Mon 2/4

CS 440: Programming Languages and Translators, Spring 2019 Mon 2/4 Haskell, Part 5 CS 440: Programming Languages and Translators, Spring 2019 Mon 2/4 More Haskell Miscellaneous topics Simple I/O, do blocks, actions Modules data vs type declaration Instances of classtypes

More information

Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont.

Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont. CMSC 330: Organization of Programming Languages OCaml 1 Functional Programming Dialects of ML ML (Meta Language) Univ. of Edinburgh,1973 Part of a theorem proving system LCF The Logic of Computable Functions

More information

Modules and Representa/on Invariants

Modules and Representa/on Invariants Modules and Representa/on Invariants COS 326 David Walker Princeton University slides copyright 2017 David Walker permission granted to reuse these slides for non-commercial educa/onal purposes LAST TIME

More information

A Func'onal Space Model

A Func'onal Space Model A Func'onal Space Model COS 26 David Walker Princeton University slides copyright 2017 David Walker permission granted to reuse these slides for non-commercial educa'onal purposes 2 Because Halloween draws

More information

HASKELL I/O. Curt Clifton Rose-Hulman Institute of Technology. Please SVN Update your HaskellInClass folder, then open eieio.hs

HASKELL I/O. Curt Clifton Rose-Hulman Institute of Technology. Please SVN Update your HaskellInClass folder, then open eieio.hs HASKELL I/O Curt Clifton Rose-Hulman Institute of Technology Please SVN Update your HaskellInClass folder, then open eieio.hs SEPARATION OF CONCERNS Haskell separates pure code from side-effecting code

More information

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II) Processadors de Llenguatge II Functional Paradigm Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra Paradigm Shift Imperative Paradigm State Machine

More information

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example CMSC 330: Organization of Programming Languages OCaml 2 Higher Order Functions Tuples Constructed using (e1,..., en) Deconstructed using pattern matching Patterns involve parens and commas, e.g., (p1,p2,

More information

To figure this out we need a more precise understanding of how ML works

To figure this out we need a more precise understanding of how ML works Announcements: What are the following numbers: 74/2/70/17 (2:30,2:30,3:35,7:30) PS2 due Thursday 9/20 11:59PM Guest lecture on Tuesday 9/25 o No RDZ office hours next Friday, I am on travel A brief comment

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Type Systems, Names and Binding CMSC 330 - Spring 2013 1 Topics Covered Thus Far! Programming languages Ruby OCaml! Syntax specification Regular expressions

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages h"p://www.di.unipi.it/~andrea/dida2ca/plp- 15/ Prof. Andrea Corradini Department of Computer Science, Pisa Monads in Haskell The IO Monad Lesson 27! 1 Pros of FuncConal

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 21 March 6 th, 2015 Transi@on to Java CIS 120 Overview Declara@ve (Func@onal) programming persistent data structures recursion is main control structure

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information