CSCE 314 Programming Languages Functors, Applicatives, and Monads

Similar documents
CSCE 314 Programming Languages

Shell CSCE 314 TAMU. Functions continued

1. Function Type Declarations (12 points):

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

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

CSCE 314 Programming Languages. Interactive Programming: I/O

College Functors, Applicatives

CSCE 314 Programming Languages

Advanced Functional Programming

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

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

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

Applicative, traversable, foldable

Applicative, traversable, foldable

CSCE 314 Programming Languages. Monadic Parsing

EECS 700 Functional Programming

CSCE 314 Programming Languages. Functional Parsers

Programming with Math and Logic

Advanced Type System Features Tom Schrijvers. Leuven Haskell User Group

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

Haskell Types, Classes, and Functions, Currying, and Polymorphism

Types in Programming Languages Dynamic and Static Typing, Type Inference (CTM 2.8.3, EPL* 4) Abstract Data Types (CTM 3.7) Monads (GIH** 9)

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

Monads. COS 441 Slides 16

Shell CSCE 314 TAMU. Higher Order Functions

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

Shell CSCE 314 TAMU. Haskell Functions

CSCE 314 Programming Languages

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

Advances in Programming Languages

Monads. Functional Programming (CS4011) Monads

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

Functional Programming

A general introduction to Functional Programming using Haskell

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

Monads in Haskell. Nathanael Schilling. December 12, 2014

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

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

State Monad (3D) Young Won Lim 9/25/17

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

Lambda-termide redutseerimine

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

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

INTRODUCTION TO HASKELL

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

Monads. Bonus lecture 2017 David Sands

CS 320: Concepts of Programming Languages

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

Lecture 4: Higher Order Functions

Monads seen so far: IO vs Gen

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

CSCE 314 Programming Languages. Monadic Parsing

CSCE 314 Programming Languages

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

CS 457/557: Functional Languages

1 Delimited continuations in Haskell

Haskell Refresher Informatics 2D

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

CS 209 Functional Programming

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

Discrete Structures Lecture 15

Functional Logic Design Patterns

The essence of dataflow programming. Teooriapäevad Kokel 2,

Programming Language Concepts: Lecture 14

Profunctor Optics: Modular Data Accessors

Programming Language Concepts, CS2104 Lecture 7

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

Software System Design and Implementation

Haskell Monads CSC 131. Kim Bruce

Complexity of Algorithms

Comonads, Applicative Functors, Monads

GADTs. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 7. [Faculty of Science Information and Computing Sciences]

Standard prelude. Appendix A. A.1 Classes

GADTs. Alejandro Serrano. AFP Summer School. [Faculty of Science Information and Computing Sciences]

List Processing in Ocaml

CSC324 Principles of Programming Languages

Example: A Compiler Fragment (1) Example: A Compiler Fragment (2) Example: A Compiler Fragment (3)

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

Functional Programming Concepts for Data Processing

Part 20. Sorting and Selection

More on functional programming

An introduction introduction to functional functional programming programming using usin Haskell

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

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

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

JVM ByteCode Interpreter

02157 Functional Programming. Michael R. Ha. Disjoint Unions and Higher-order list functions. Michael R. Hansen

Functional Logic Programming Language Curry

CMSC 330: Organization of Programming Languages. OCaml Higher Order Functions

CMSC 330: Organization of Programming Languages. OCaml Higher Order Functions

CMSC 330: Organization of Programming Languages. OCaml Higher Order Functions

Lazy Functional Programming in Haskell

CSCE 314 Programming Languages. Type System

Principles of Programming Languages (H)

Box-and-arrow Diagrams

Monads and More: Part 3

Haskell Overview II (2A) Young Won Lim 9/26/16

Functional Programming TDA 452, DIT 142

Representing Cyclic Structures as Nested Datatypes. Makoto Hamana

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

Transcription:

CSCE 314 Programming Languages Functors, Applicatives, and Monads Dr. Hyunyoung Lee 1

Motivation Generic Functions A common programming pattern can be abstracted out as a definition. For example: inc :: [Int] -> [Int] inc [] = [] inc (n:ns) = n+1 : inc ns sqr :: [Int] -> [Int] sqr [] = [] sqr (n:ns) = n^2 : sqr ns Both functions are defined in the same manner! 2

inc :: [Int] -> [Int] inc [] = [] inc (n:ns) = n+1 : inc ns inc = map (+1) sqr :: [Int] -> [Int] sqr [] = [] sqr (n:ns) = n^2 : sqr ns Using map sqr = map (^2) map :: (a -> b) -> [a] -> [b] map f [] = [] map f (n:ns) = f n : map f ns 3

Functors Class of types that support mapping of function. For example, lists and trees. class Functor f where fmap :: (a -> b) -> f a -> f b (f a) is a data structure that contains elements of type a fmap takes a function of type (a->b) and a structure of type (f a), applies the function to each element of the structure, and returns a structure of type (f b). Functor instance example 1: the list structure [] instance Functor [] where -- fmap :: (a -> b) -> [a] -> [b] fmap = map 4

Functor instance example 2: the Maybe type data Maybe a = Nothing Just a instance Functor Maybe where -- fmap :: (a -> b) -> Maybe a -> Maybe b fmap _ Nothing = Nothing fmap g (Just x) = Just (g x) Now, you can do > fmap (+1) Nothing Nothing > fmap not (Just True) Just False 5

Functor instance example: the Maybe type (Cont.) Picture source: http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html 6

Functor instance example 3: the Tree type data Tree a = Leaf a Node (Tree a) (Tree a) deriving show instance Functor Tree where -- fmap :: (a -> b) -> Tree a -> Tree b fmap g (Leaf x) = Leaf (g x) fmap g (Node l r) = Node (fmap g l) (fmap g r) Now, you can do > fmap (+1) (Node (Leaf 1) (Leaf 2)) Node (Leaf 2) (Leaf 3) > fmap (even) (Node (Leaf 1) (Leaf 2)) Node (Leaf False) (Leaf True) 7

Functor laws 1. fmap id = id 2. fmap (g. h) = fmap g. fmap h 1. fmap preserves the identity function 2. fmap also preserves the function composition, where g has type b -> c and h has type a -> b 3. The functor laws ensure that fmap does perform a mapping operation, without altering the natural property of the data structure. 8

Benefits of Functors 1. fmap can be used to process the elements of any structure that is functorial. 2. Allows us to define generic functions that can be used with any functor. Example: increment (inc) function can be used with any functor with Int type elements inc :: Functor f => f Int -> f Int inc = fmap (+1) > inc (Just 1) Just 2 > inc [1,2,3] [2,3,4] > inc (Node (Leaf 1) (Leaf 2)) Node (Leaf 2) (Leaf 3) 9

Want to be more flexible? Functors abstract the idea of mapping a function over each element of a structure. class Functor f where fmap :: (a -> b) -> f a -> f b Only one argument function! The first argument of fmap is a function that takes one argument, but we want more flexibility! We want to be able to use functions that take any number of arguments. class Functor f => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b 10

Applicative class (Functor f) => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b The function pure takes a value of any type as its argument and returns a structure of type f a, that is, an applicative functor that contains the value. The operator <*> is a generalization of function application for which the argument function, the argument value, and the result value are all contained in f structure. <*> associates to the left: ( (pure g <*> x) <*> y) <*> z fmap g x = pure g <*> x = g <$> x 11

Applicative functor instance example 1: Maybe data Maybe a = Nothing Just a instance Applicative Maybe where -- pure :: a -> Maybe a pure = Just -- (<*>) :: Maybe (a->b) -> Maybe a -> Maybe b Nothing <*> _ = Nothing (Just g) <*> mx = fmap g mx > pure (+1) <*> Nothing Nothing > pure (+) <*> Just 2 <*> Just 3 Just 5 > mult3 x y z = x*y*z > pure mult3 <*> Just 1 <*> Just 2 <*> Just 4 Just 8 12

Applicative functor instance example: Maybe (Cont.) Picture source: http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html 13

Applicative functor instance example 2: list type [] instance Applicative [] where -- pure :: a -> [a] pure x = [x] -- (<*>) :: [a -> b] -> [a] -> [b] gs <*> xs = [ g x g <- gs, x <- xs ] pure transforms a value into a singleton list. <*> takes a list of functions and a list of arguments, and applies each function to each argument in turn, returning all the results in a list. > pure (+1) <*> [1,2,3] [2,3,4] > pure (+) <*> [1,3] <*> [2,5] [3,6,5,8] > pure (:) <*> "ab" <*> ["cd","ef"] ["acd","aef","bcd","bef"] 14

Applicative functor instance example: [] (Cont.) > [(*2), (+3)] <*> [1,2,3] [2,4,6,4,5,6] Lee CSCE 314 TAMU Picture source: http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html 15

Applicative laws pure id <*> x pure (g x) x <*> pure y = x = pure g <*> pure x = pure (\g -> g y) <*> x x <*> (y <*> z) = (pure (.) <*> x <*> y) <*> z 1. pure preserves the identity function 2. pure also preserves function application 3. When an effectful function is applied to a pure argument, the order in which the two components are evaluated does not matter. 4. The operator <*> is associative (modulo types that are involved). 16

Monads class (Applicative m) => Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b return = pure Roughly, a monad is a strategy for combining computations into more complex computations. Another pattern of effectful programming (applying pure functions to (side-)effectful arguments) (>>=) is called bind operator. Note: return may be removed from the Monad class in the future, and become a library function instead. 17

Monad instance example 1: Maybe data Maybe a = Nothing Just a instance Monad Maybe where -- (>>=):: Maybe a -> (a -> Maybe b) -> Maybe b Nothing >>= _ = Nothing (Just x) >>= f = f x div2 x = if even x then Just (x `div` 2) else Nothing > (Just 10) >>= div2 Just 5 > (Just 10) >>= div2 >>= div2 Nothing > (Just 10) >>= div2 >>= div2 >>= div2 Nothing 18

Monad instance example 2: list type [] instance Monad [] where -- (>>=) :: [a] -> (a -> [b]) -> [b] xs >>= f = [y x <- xs, y <- f x] pairs :: [a] -> [b] -> [(a,b)] pairs xs ys = do x <- xs y <- ys return (x,y) > pairs [1,2] [3,4] [(1,3),(1,4),(2,3),(2,4)] pairs xs ys = xs >>= \x -> ys >>= \y -> return (x,y) 19

Monad laws return x >>= f mx >>= return = f x - left identity = mx -- right identity (mx >>= f) >>= g = mx >>= (\x -> (f x >>= g)) 1. If we return a value and then feed it into a monadic function, this should give the same result as simply applying the function to the value. 2. If we feed the result of a monadic computation into the function return, this should give the same result as simply performing the computation. 3. >>= is associative 20