Monads Technion – Institute of Technology Software Design (236700) Author: Gal Lalouche - Technion 2016 © 1.

Slides:



Advertisements
Similar presentations
CS162 Week 2 Kyle Dewey. Overview Continuation of Scala Assignment 1 wrap-up Assignment 2a.
Advertisements

Written by: Dr. JJ Shepherd
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Java 8 Technion – Institute of Technology Software Design (236700) Based on slides by: Sagie Davidovich, Assaf Israel Author: Assaf Israel - Technion 2013.
Feature requests for Case Manager By Spar Nord Bank A/S IBM Insight 2014 Spar Nord Bank A/S1.
MATHEMATICAL FOUNDATIONS SUPPLEMENTAL MATERIAL – NOT ON EXAM.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
Introducing Monads Lecture 3, Designing and Using Combinators John Hughes.
Programming in Scala Chapter 1. Scala: both object-oriented and functional Scala blends –object-oriented and –functional programming in a –statically.
1 Thread Pools. 2 What’s A Thread Pool? A programming technique which we will use. A collection of threads that are created once (e.g. when server starts).
Proxy Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
Week 14 - Monday.  What did we talk about last time?  Image manipulation  Inheritance.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Monads Technion – Institute of Technology Software Design (236700) Author: Gal Lalouche - Technion 2015 © 1.
Java 8 Lambda expressions and you Technion – Institute of Technology Software Design (236700) Based on slides by: Sagie Davidovich, Assaf Israel Author:
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Chapter 3 Introduction to Collections – Stacks Modified
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
CSC 580 – Theory of Programming Languages, Spring, 2009 Week 9: Functional Languages ML and Haskell, Dr. Dale E. Parson.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
Dependency Injection Technion – Institute of Technology Author: Gal Lalouche - Technion 2015 ©
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
Objects & Dynamic Dispatch CSE 413 Autumn Plan We’ve learned a great deal about functional and object-oriented programming Now,  Look at semantics.
Recap form last time How to do for loops map, filter, reduce Next up: dictionaries.
© M. Winter COSC 4P41 – Functional Programming Programming with actions Why is I/O an issue? I/O is a kind of side-effect. Example: Suppose there.
Exceptions, cont’d. Factory Design Pattern COMP 401 Fall 2014 Lecture 12 9/30/2014.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
CS162 Week 1 Kyle Dewey. Overview Basic Introduction CS Accounts Scala survival guide.
Design Patterns David Talby. This Lecture Re-routing method calls Chain of Responsibility Coding partial algorithms Template Method The Singleton Pattern.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Interactive Programs: I/O and Monads Dr. Hyunyoung Lee.
Inside LINQ to Objects How LINQ to Objects work Inside LINQ1.
Dependency Injection Frameworks Technion – Institute of Technology Author: Assaf Israel - Technion 2013 ©
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Java8 Released: March 18, Lambda Expressions.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
OOP Basics Classes & Methods (c) IDMS/SQL News
Dependency Injection with Guice Technion – Institute of Technology Author: Gal Lalouche - Technion 2016 ©
Spartan Programming Technion – Institute of Technology Author: Gal Lalouche - Technion 2016 © 1 “Minimalism isn't always the right choice, but it's.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
Java 8 Lambda Expressions and You Technion – Institute of Technology Software Design (236700) Based on slides by: Sagie Davidovich, Assaf Israel Author:
Today Encapsulation. Build a fully encapsulated Halloween class, going from Halloween1 to Halloween6 (eventually!): –The final version will have overloaded.
Java 8, Lambda Expressions and You
Functional Programming and Stream API
Containers and Lists CIS 40 – Introduction to Programming in Python
Monads Author: Gal Lalouche - Technion 2017 © 1 1.
Functional Programming with Java
CMPE212 – Stuff… Exercises 4, 5 and 6 are all fair game now.
PROGRAMMING IN HASKELL
Lesson Objectives Aims
Computation Abstraction Going beyond programming language glue, or what we've missed from FP for so long in mainstream  googlewave.com!w+PgcakhgiA 
PROGRAMMING IN HASKELL
Arrays and Collections
Statement-Level Control Structures
Programming Languages
Software Engineering and Architecture
Promises.
Presentation transcript:

Monads Technion – Institute of Technology Software Design (236700) Author: Gal Lalouche - Technion 2016 © 1

Monads - motivation Consider this simple code: What happens when we need to handle nulls ? Author: Gal Lalouche - Technion 2016 © 2 Student s = getStudent(); if (s == null) return null; Course c = s.getCourse("Software Design"); if (c == null) return null; MoedA m = c.getMoedA(); if (m == null) return null; return m.getGrade(); return getStudent().getCourse("Software Design").getMoedA().getGrade()

 We already saw the Optional monad last week  If everything returned an Optional, we could greatly simply our code: Monads - solution Author: Gal Lalouche - Technion 2016 © 3 class Optional { public static Optional of(T t) { return new Optional(t); // throws exception on null } public Optional flatMap(Function > f) { return this == Optional.empty() ? this : Optional.ofNullable(f.apply(get())); } return getStudent().flatMap(x -> x.getCourse("Software Design")).flatMap(x -> x.getMoedA()).flatMap(x -> x.getGrade());

What is a Monad? What? Author: Gal Lalouche - Technion 2016 © 4

What is a Monad?  In Haskell, it is defined thusly:  Okay, and in English (i.e., Java)? Author: Gal Lalouche - Technion 2016 © 5 class Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b -- sometimes called bind class Monad { public static Monad of(T t); // return public Monad flatMap(Function > f); // >>= }

What is a Monad? (Cont.) A proper Monad needs to satisfy the Three Monadic Laws: I.Left Identit y : Monad.of(x).flatMap(f) === f.apply(x) II.Right Identity: m.flatMap(x -> Monad.of(x)) === m III.Associativity: m.flatMap(f).flatMap(g) === m.flatMap(x -> f.apply(x).flatMap(g)) These are the exact laws of a monoid, where of is the identity element, and flatMap is the binary operation Author: Gal Lalouche - Technion 2016 © 6

But wait, what about get, map and other higher-order functions? flatMap and of is enough to implement everything! We can implement foreach and map : In the real world, we may implement these differently (for performance, etc.), but the important thing is that flatMap and of are sufficient for implementing this. Author: Gal Lalouche - Technion 2016 © 7 class Monad { public void foreach(Consumer f) { flatMap(t -> {f.accept(t); return this;}); } public Monad map(Function f) { return flatMap(t -> of(f.apply(t))); }

Examples of Monads: Try  Sometimes, Optional is not enough  If Optional is explicitly returning null, how do we explicitly throw an exception?  Checked exceptions are too verbose, and work on a method level, rather than at a variable level 8 Author: Gal Lalouche - Technion 2016 © class Try { public static Try of(T t) { return new Success(t); } // this isn't the Monad's of! public static Try of(Callable c) { try { return of(c.call()); } catch (Exception e) { return new Failure(e); } public T get(); } class Success extends Try { … } class Failure extends Try { … }

Examples of Monads (Cont.)  We've seen Optional and Try  List is also a Monad!  Many of the names given to methods make more sense for lists, e.g., foreach on most monads accesses just a single element, but it iterates over all elements in a list  In Java, Stream is the only monadic implementation of a collection  In Haskell, IO is a way to encapsulate state changing functions, in a language that has no concept of change (i.e., a pure language)  For example, reading input, printing output, side effects including mutability  Next we will examine Future in depth Author: Gal Lalouche - Technion 2016 © 9

So what are Monads good for exactly?  Optional and Try allow us to encapsulate failure  Our code may yield nothing  Or throw an exception  List/Stream encapsulates plurality  Also non-determinism: we don't know how many elements will be returned; could be none, one, or multiple  IO encapsulates side effects  Future encapsulates asynchronicity Author: Gal Lalouche - Technion 2016 © 10

Monads make the context explicit  Monads let us encapsulate and structure contexts  The context, assumptions and side effects of computations are made explicit rather than implicit  We can transform our data using the same functions 11

The Future Monad - motivation Suppose we have a task that takes a very long time :  How should handle this?  Blocking until all tasks are complete is sometimes unacceptable  For example, in a user interface  The asynchronous way is to use callback : Author: Gal Lalouche - Technion 2016 © 12 List getAlbum(String name) { Profile p = getProfile(name); // fetches data from remote server List as = getAlbums(p); // fetches data … Album a = find(as, "Thailand"); // fetches data … return getPictures(a); // fetches data … } void getAlbum(String name, Consumer > callback) { new Thread(() -> callback.accept(getAlbum(name))).start(); }

The Future Monad - motivation (Cont.)  What if want to compose such callbacks?  This (painful) pattern should be familiar to anyone who programmed using AJAX or similar frameworks  The problem is that instead of holding T, we're holding a Future of T  When we want to compose abstractions of generic types, we want Monads ! Author: Gal Lalouche - Technion 2016 © 13 callback1(params1, t1 -> callback2(params2, t2 -> callback3(params3, t3 -> …) … ) );

The Future Monad Author: Gal Lalouche - Technion 2016 © 14 class Future { private Thread thread; private T value = null; public Future(Supplier s) { this.thread = new Thread(() -> { this.value = s.get(); }); this.thread.start(); } public T get() { thread.join(); return value; } // Monadic functions: public static Future of(T t) { // if we want, we can optimize this to be threadless return new Future<>(() -> t); } public Future flatMap(Function > f) { return new Future<>(() -> f.apply(this.get()).get()); }

The Future Monad - usage But wait! What about a callback ?  That's exactly the default foreach implementation  Reminder:  Usage in Future: Author: Gal Lalouche - Technion 2016 © 15 public void foreach(Consumer f) { flatMap(t -> {f.accept(t); return this;}); } new Future<>(() -> { long start = System.currentTimeMillis(); for (long i = 1; i < L; i++){} return System.currentTimeMillis() - start; }).foreach(System.out::println);

The Future Monad – usage (Cont.)  Our transformed code is much cleaner:  What if we want to use transformations that are synchronous?  We use map of course! Author: Gal Lalouche - Technion 2016 © 16 Future > getAlbum(String name) { return getProfile(name).flatMap(p -> getAlbums(p)).flatMap(as -> find(as, "Thailand")).flatMap(a -> getPictures(a)); }

Additive Monads – Monads that are also Monoids Some monads have two more properties: 1.An empty instance e.g., an empty List ( Nil, [] ), Optional.empty(), a Future that throws an exception Will usually be implemented as a singleton (Do we need more than one empty list?) 2. A plus operator e.g., List concatenation ( ++ ) Trivial implementation (In the next slide, we will see why it's valid) Author: Gal Lalouche - Technion 2016 © 17 public Monad plus(Monad other) { return this == empty ? other : this; }

Additive Monads (Cont.) the following laws apply 1.m.plus(empty) === m (additive identity) 2.empty.plus(m) === m (additive identity) 3.empty.flatMap(f) === empty (multiplicative identity) 4.m.flatMap(empty) === empty (multiplicative identity) 5.m1.plus(m2).plus(m3) === m1.plus(m2.plus(m3)) (Assoc.) (But I thought Monads were already monoids! A monad is a monoid in the category of endofunctors. In layman’s terms, the methods of the monads are the elements in) Author: Gal Lalouche - Technion 2016 © 18

Additive Monads – Why? We can implement filter using empty : We can recover from failure with plus (not part of Java’s optional) This is also called null coalescing. In C#, we use ?? for nulls. Or with Try: Author: Gal Lalouche - Technion 2016 © 19 public Monad filter(Predicate p) { return flatMap(t -> p.test(t) ? of(t) : empty); } getOptional1().getOrElse(getOptional2()).getOrElse(getOptional3()) try1.recoverWith(try2()).recoverWith(try3())

Further Reading cdsmith.wordpress.com/2012/04/18/why-do-monads-matter/ (Language Agnostic / Haskellish) cdsmith.wordpress.com/2012/04/18/why-do-monads-matter/ wiki.haskell.org/All_About_Monads (Haskell) wiki.haskell.org/All_About_Monads learnyouahaskell.com/a-fistful-of-monads (Haskell) learnyouahaskell.com/a-fistful-of-monads (Scala) github.com/ReactiveX/RxJava (Java) github.com/ReactiveX/RxJava Author: Gal Lalouche - Technion 2016 © 20

Appendix: Fluent APIs In object-oriented languages, monadic transformations are chained in the order that they are evaluated: Examples include Java’s Stream, C# LINQ (with IEnumerable ), Ruby’s Enumerable module, and even bash piping. Without fluent APIs, we have to read functions in reverse order: Languages with non-fluent API: ML, Haskell, Python, C++, Lisp(s) Author: Gal Lalouche - Technion 2016 © 21 stream.map(x -> x * x).filter(x -> x % 3 == 0).map(x -> x + 8).sum() sum( map(x -> x + 8, filter(x -> x % 3 == 0, map(x -> x * x, list))))

Fluent APIs (cont.) Often enough, any API that returns this from method calls is called Fluent This pattern is especially common with builder objects But unlike monds, it doesn’t reverse the order of reading: vs. It’s possible to transform non-fluent APIs to fluent APIs either with wrapping / decorators, or special functions (e.g., in Haskell/F#: x |> f = f x ) Author: Gal Lalouche - Technion 2016 © 22 new Builder().setX(x).setY(y).build(); Builder b = new Builder() b.setX(x) b.setY(y) b.build();

Appendix: Monads and Monoids I thought monads were already monoids! Why are “additive monads” special? Monads are monoids in the category of endofunctors. In other words, it’s not the monad instances themselves that form a monoid, but their methods. Identity: static of method Binary associative operator: flatMap method In a monoid class, the instances of the class are the elements of the monoid: Identity: empty (a special object) Binary associative operator: plus adds two instances to get a new instance Another way to think about it is this: Monads are parametric ( Monad ); monoids aren’t (Integers are monoids but not monads). Author: Gal Lalouche - Technion 2016 © 23

Appendix: Monads in Haskell In languages with a richer type-system than Java, like Haskell or Scala, Monads are much more interesting/useful This is because you can write code that works on a general Monad For example, in our java implementation we have to implement map, foreach, filter, etc. for every new Monad class we define If we had typeclasses, we could implement it just once, for all monads! Author: Gal Lalouche - Technion 2016 © 24