Monads. Bonus lecture 2017 David Sands

Similar documents
Monads seen so far: IO vs Gen

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

More on functional programming

Monads and all that III Applicative Functors. John Hughes Chalmers University/Quviq AB

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

EECS 700 Functional Programming

Monads and all that I. Monads. John Hughes Chalmers University/Quviq AB

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

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

Monad (3A) Young Won Lim 8/9/17

Parsing Expressions. Slides by Koen Lindström Claessen & David Sands

CSCE 314 Programming Languages Functors, Applicatives, and Monads

Applicative, traversable, foldable

Monad P1 : Several Monad Types (4A) Young Won Lim 2/13/19

Monad Overview (3B) Young Won Lim 1/16/18

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

Maybe Monad (3B) Young Won Lim 1/3/18

Functional Programming

Applicative, traversable, foldable

Maybe Monad (3B) Young Won Lim 12/21/17

Expressions. Parsing Expressions. Showing and Reading. Parsing. Parsing Numbers. Expressions. Such as. Can be modelled as a datatype

Parsing. Zhenjiang Hu. May 31, June 7, June 14, All Right Reserved. National Institute of Informatics

Programming in Haskell Aug Nov 2015

Monads. Functional Programming (CS4011) Monads

Standard prelude. Appendix A. A.1 Classes

CIS552: Advanced Programming

Functional Programming TDA 452, DIT 142

Overview. Declarative Languages. General monads. The old IO monad. Sequencing operator example. Sequencing operator

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

Haskell Monads CSC 131. Kim Bruce

Monad (1A) Young Won Lim 6/26/17

I/O in Haskell. To output a character: putchar :: Char -> IO () e.g., putchar c. To output a string: putstr :: String -> IO () e.g.

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

Polymorphism Overview (1A) Young Won Lim 2/20/18

Fusion-powered EDSLs

The Remote Monad. Dissertation Defense. Justin Dawson.

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Functional Parsers

Monads. COS 441 Slides 16

Software System Design and Implementation

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

College Functors, Applicatives

Introduction to Haskell

JVM ByteCode Interpreter

Monad class. Example: Lambda laughter. The functional IO problem. EDAN40: Functional Programming Functors and Monads

Programming Languages

CSCE 314 Programming Languages. Functional Parsers

Solution sheet 1. Introduction. Exercise 1 - Types of values. Exercise 2 - Constructors

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

CSCE 314 Programming Languages. Monadic Parsing

All About Comonads (Part 1) An incomprehensible guide to the theory and practice of comonadic programming in Haskell

Advanced Functional Programming

Type system. Type theory. Haskell type system. EDAN40: Functional Programming Types and Type Classes (revisited)

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

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

Monads in Haskell. Nathanael Schilling. December 12, 2014

Functional Programming TDA 452, DIT 142

QuickCheck: Beyond the Basics

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

INDEX. Symbols & Numbers. Learn You a Haskell for Great Good! 2011 by Miran Lipovača

DerivingVia or, How to Turn Hand-Written Instances into an Anti-Pattern

Embedded Domain Specific Languages in Idris Lecture 3: State, Side Effects and Resources

INTRODUCTION TO HASKELL

Livin la via loca Coercing Types with Class

CS 11 Haskell track: lecture 4. n This week: Monads!

Monad (1A) Young Won Lim 6/21/17

CSCE 314 Programming Languages

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

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

COMP3141 Assignment 2

CS 320: Concepts of Programming Languages

CS 209 Functional Programming

CSCE 314 Programming Languages. Interactive Programming: I/O

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

Monad (1A) Young Won Lim 6/9/17

Haskell Modules. Input and Output. Urtė Zubkaitė

CSC324 Principles of Programming Languages

PROGRAMMING IN HASKELL. Chapter 10 - Interactive Programming

State Monad (3D) Young Won Lim 8/31/17

Programming with Math and Logic

GHCi: Getting started (1A) Young Won Lim 6/3/17

Introduction to Functional Programming and Haskell. Aden Seaman

CSCE 314 Programming Languages. Monadic Parsing

CSCE 314 Programming Languages. Type System

CS 360: Programming Languages Lecture 12: More Haskell

GHCi: Getting started (1A) Young Won Lim 5/31/17

1. Function Type Declarations (12 points):

CS 457/557: Functional Languages

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

Part 0. A (Not So) Brief Introduction to Haskell

Lazy Functional Programming in Haskell

Informatics 1 Functional Programming Lecture 11. Data Representation. Don Sannella University of Edinburgh

Trees. Solution: type TreeF a t = BinF t a t LeafF 1 point for the right kind; 1 point per constructor.

Parsing Combinators: Introduction & Tutorial

Lecture 4: Higher Order Functions

Lecture 8: Summary of Haskell course + Type Level Programming

CIS 194: Homework 5. Due Friday, October 3, Rings. No template file is provided for this homework. Download the

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

Haskell & functional programming, some slightly more advanced stuff. Matteo Pradella

Principles of Programming Languages (H)

Haskell Overloading (1) LiU-FP2016: Lecture 8 Type Classes. Haskell Overloading (3) Haskell Overloading (2)

Transcription:

Monads Bonus lecture 2017 David Sands

Our version of the story, so far. Monad is the class of instructions. Instructions can be built using do notation. We have seen two kinds of instructions i.e. two instances of Monad: IO do putstr File name? f <- getline c <- readfile f return $ f ++ c Gen do n <- choose (2,10) r <- elements[clubs,spades] return $ Card r (Numeric n)

IO vs Gen IO T Gen T Instructions to build a value of type T by interacting with the operating system Instructions to create a random value of type T Run by the ghc runtime system Run by the QuickCheck library functions to perform random tests

Repeating Instructions dotwice i = do a <- i b <- i return (a,b) Main> dotwice $ putstrln "hello hello hello ((),()) Main>

Repeating Instructions dotwice i = do a <- i b <- i return (a,b) Main> sample $ dotwice (choose ( a, z )) ('m','c') ('b','j') ('h','l') ('y','q') ('k','f') ('w','q') ('p','h') Main>

Monads = Instructions What is the type of dotwice? Main> :t dotwice dotwice :: Monad a => a b -> a (b,b) Even the kind of instructions can vary. Different kinds of instructions, depending on who obeys them. Whatever kind of result it produces, we get a pair of them IO means operating system.

Plan 1. One more example of a Monad: Instructions for Parsing (a parsing library) 2. Rolling your own Monads The Truth about do The Parser Monad Maybe is also a Monad (and list, and...

A Simple Parsing Library A library for building parsers containing: An abstract data type Parser a A function parse :: Parser a -> String -> Maybe (a,string) Basic building blocks for building parsers

Example: Phone numbers Two ways of writing phone numbers: +46 317721000 0317721000

do s <- getline IO c <- readfile s return $ s ++ c do n <- elements[1..9] Gen m <- vectorof n arbitrary return $ n:m do c <- sat (`elem` ;,: ) ds <- chain digit (char c) return $ map digittoint ds Parser

IO t Instructions for interacting with operating system Run by GHC runtime system produce value of type t Gen t Instructions for building random values Run by quickcheck to generate random values of type t Parser t Instructions for parsing Run by parse to parse a string and produce a Maybe (t,string)

Terminology A monadic value is just an expression whose type is an instance of class Monad t is a monad means t is an instance of the class Monad We have often called a monadic value an instruction. This is not standard terminology but sometimes they are called actions

Monads and do notation To be an instance of class Monad you need (as a minimal definition) operations >>= and return class Monad m where (>>=) :: m a -> (a -> m b) -> m b return :: a -> m a (>>) :: m a -> m b -> m b x >> y = x >>= \_ -> y Default implementations fail :: String -> m a fail msg = error msg

Update, As of GHC 7.10 OK that s a bit old school. Nowadays Monad is a subclass of Applicative (which is a subclass of Functor) The class itself is a bit simpler you just need to define >>= But I ll define it the old way and ignore the rest

Boilerplate to make your monad an instance of Applicative import Control.Applicative (Applicative(..)) import Control.Monad(liftM, ap) instance Functor MyMonad where fmap = liftm instance Applicative MyMonad where pure = return (<*>) = ap See Learn you a Haskell for more info on Functor and Applicative

The truth about Do Do syntax is just a shorthand: do act1 == == act2 act1 >> act2 act1 >>= \_ -> act2 do v <- act1 == act2 act1 >>= \v -> act2

The Parser Monad To be an instance of class Monad you need two operations: >>= and return instance Monad Parser where return = succeed (>>=) = (>*>) Why bother? Our first example of a home-grown monad Can understand do notation

Example

The truth about Do Full translation (I) do act1 actn act1 >> do actn == = do v <- act1 actn == act1 >>= \v -> do actn do actn == actn

The truth about Do Full Translation (II): Let and pattern matching do let p = e actn let p = e in do actn == = do pattern <- act1 actn == == let f pattern = do actn f _ = fail Error in act1 >>= f

All three functions take a value (or no value) and produce an IO wrapped value The function >>= allows us to join them together getline >>= readfile >>= putstrln

Maybe

Here is a function

They can be composed

Here is a function half x even x = Just (x `div` 2) odd x = Nothing

What if we feed it a wrapped value? We need to use >>= to shove our wrapped value into the function

>>=

>>=

>>=

>>=

>>=

Just 20 >>= half >>= half >>= half

Instance Monad Maybe Maybe is a very simple monad instance Monad Maybe where Just x >>= k = k x Nothing >>= _ = Nothing return fail s = Just = Nothing Although simple it can be useful

Congestion Charge Billing

Congestion Charge Billing Registration number used to find the Personnummer of the owner carregister :: [(RegNr,PNr)] Personnummer used to find the name of the owner nameregister :: [(PNr,Name)] Name used to find the address of the owner addressregister :: [(Name,Address)]

Example: Congestion Charge Billing type CarReg = String ; type PNr = String type Name = String ; type Address = String carregister :: [(CarReg,PNr)] carregister = [("JBD 007","750408-0909"),...] nameregister :: [(PNr,Name)] nameregister = [("750408-0909","Dave ),... ] addressregister :: [((Name,PNr),Address)] addressregister = [(("Dave","750408-0909"),"42 Streetgatan\n Askim"),... ]

Example: Congestion Charge Billing With the help of lookup :: Eq a => a -> [(a,b)] -> Maybe b we can return the address of car owners billingaddress :: CarReg -> Maybe (Name, Address) billingaddress car = case lookup car carregister of Nothing -> Nothing Just pnr -> case lookup pnr nameregister of Nothing -> Nothing Just name -> case lookup (name,pnr) addressregister of Nothing -> Nothing Just addr -> Just (name,addr)

Example: Congestion Charge Billing Using the fact that Maybe is a member of class Monad we can avoid the spaghetti and write: billingaddress car = do pnr <- lookup car carregister name <- lookup pnr nameregister addr <- lookup (name,pnr) addressregister return (name,addr)

Example: Congestion Charge Billing Unrolling one layer of the do syntactic sugar: billingaddress car == lookup car carregister >>= \pnr -> do name <- lookup pnr nameregister addr <- lookup (name,pnr) addressregister return (name,addr) lookup car carregister gives Nothing then the definition of >>= ensures that the whole result is Nothing return is Just

Summary We can use higher-order functions to build Parsers from other more basic Parsers. Parsers can be viewed as an instance of Monad We have seen how we can build our own Monads! A lot of plumbing is nicely hidden away The implementation of the Monad is not visible and can thus be changed or extended

IO t Instructions for interacting with operating system Run by GHC runtime system produce value of type t Gen t Instructions for building random values Run by quickcheck to generate random values of type t Parser t Instructions for parsing Run by parse to parse a string and Maybe produce a value of type t + Maybe = Four Monads

Code Parsing.hs module containing the parser monad and simple parser combinators. See course home page

We can build our own Monads! A lot of plumbing is nicely hidden away A powerful pattern, used widely in Haskell A pattern that can be used in other languages, but syntax support helps F# computation expressions Scala

More examples http://adit.io/posts/2013-06-10-three-usefulmonads.html stack (slides/video from last year)

Another Example: A Stack A Stack is a stateful object Stack operations can push values on, pop values off, add the top elements type Stack = [Int] newtype StackOp t = StackOp (Stack -> (t,stack)) -- the type of a stack operation that produces -- a value of type t pop :: StackOp Int push :: Int -> StackOp () add :: StackOp ()

Running a StackOp type Stack = [Int] newtype StackOp t = StackOp (Stack -> (t,stack)) run (StackOp f) = f -- run (StackOp f) state = f state

Operations

Building a new StackOp swap :: StackOp () swap = StackOp $ \s -> let (x,s') = run pop s (y,s'') = run pop s' (_,s''') = run (push x) s'' (_,s'''') = run (push y) s'' in (_, s'''') No thanks!

StackOp is a Monad Stack instructions for producing a value

So now we can write

Stack t Stack instructions producing a value of type t Run by run Maybe t Instructions for either producing a value or nothing Run by?? (not an abstract data type) Two More Monads

Pictures from a blog post about functors, applicatives and monads http://adit.io/posts/2013-04-17- functors,_applicatives,_and_monads_in_pictures.html Aditya Y. Bhargava