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

Slides:



Advertisements
Similar presentations
Formal Language, chapter 4, slide 1Copyright © 2007 by Adam Webber Chapter Four: DFA Applications.
Advertisements

CS162 Week 2 Kyle Dewey. Overview Continuation of Scala Assignment 1 wrap-up Assignment 2a.
Written by: Dr. JJ Shepherd
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Remote Method Invocation (RMI) Mixing RMI and sockets
Java 8 Technion – Institute of Technology Software Design (236700) Based on slides by: Sagie Davidovich, Assaf Israel Author: Assaf Israel - Technion 2013.
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.
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.
1 New Architectures Need New Languages A triumph of optimism over experience! Ian Watson 3 rd July 2009.
Programming in Scala Chapter 1. Scala: both object-oriented and functional Scala blends –object-oriented and –functional programming in a –statically.
Lecture 9 Concepts of Programming Languages
Factory Design Pattern, cont’d COMP 401 Fall 2014 Lecture 13 10/2/2014.
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).
COMP 14: Intro. to Intro. to Programming May 23, 2000 Nick Vallidis.
Lesson 3 Remote Method Invocation (RMI) Mixing RMI and sockets Rethinking out tic-tac-toe game.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 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
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Design patterns. What is a design pattern? Christopher Alexander: «The pattern describes a problem which again and again occurs in the work, as well as.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
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.
CSE 143 Lecture 11 Maps Grammars slides created by Alyssa Harding
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
In the name of Allah The Proxy Pattern Elham moazzen.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Test Isolation and Mocking Technion – Institute of Technology Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2015 ©
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
1 Web Based Programming Section 8 James King 12 August 2003.
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
Dependency Injection Technion – Institute of Technology Author: Gal Lalouche - Technion 2015 ©
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
1 Interfacing & embedding. 2 References  Full tutorial and references Embedding and Interfacing Manual Windows - select “Documentation” from the ECLiPSe.
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.
1 6th Workshop "SEERE", Ravda, September 2006 OOJava course materials – what happened during last year? M. Ivanovic, K. Bothe.
Advanced C# Types Tom Roeder CS fa. From last time out parameters difference is that the callee is required to assign it before returning not the.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Interactive Programs: I/O and Monads Dr. Hyunyoung Lee.
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 TESTING B MODULE 2: SOFTWARE SYSTEMS 22 NOVEMBER 2013.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
The Singleton Pattern (Creational)
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
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:
Monads Technion – Institute of Technology Software Design (236700) Author: Gal Lalouche - Technion 2016 © 1.
Test Isolation and Mocking Technion – Institute of Technology Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2016 ©
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
PROGRAMMING IN HASKELL
Arrays and Collections
Programming Languages
CMSC 202 Exceptions.
Software Engineering and Architecture
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

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

Monads - motivation Consider this simple code: What happens when we need to handle nulls ? Author: Gal Lalouche - Technion 2015 © 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 in the first tutorial!  If everything returned an Optional, we could greatly simply our code: Monads - solution Author: Gal Lalouche - Technion 2015 © 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 2015 © 4

What is a Monad?  In Haskell, it is defined thusly:  Okay, and in English (i.e., Java)? Author: Gal Lalouche - Technion 2015 © 5 class Functor m => Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b// also 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 2015 © 6

But wait, what about get, map and other higher-order functions? flatMap is enough to implement everything, because we can implement foreach and map : In the real world, we may implement these differently, but the important thing is that flatMap is sufficient Author: Gal Lalouche - Technion 2015 © 7 class Monad { public void foreach(Consumer f) { // do in Haskell 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 2015 © 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.)  So we've seen Optional and Try  List is also a Monad!  Practically any generic data structure is Monadic  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, and random number generators  Today, we will examine Future in depth Author: Gal Lalouche - Technion 2015 © 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 encapsulates plurality  Also non-determinism: we don't know how many elements will be returned; could be none, one, or multiple  IO encapsulates state and mutability  Future encapsulates asynchronicity Author: Gal Lalouche - Technion 2015 © 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 Author: Gal Lalouche - Technion 2015 © 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 2015 © 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 2015 © 13 callback1(params1, t1 -> callback2(params2, t2 -> callback3(params3, t3 -> …) … ) );

The Future Monad Author: Gal Lalouche - Technion 2015 © 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 of Future: Author: Gal Lalouche - Technion 2015 © 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 2015 © 16 Future > getAlbum(String name) { return getProfile(name).flatMap(p -> getAlbums(p)).flatMap(as -> find(as, "Thailand")).flatMap(a -> getPictures(a)); }

Additive Monads 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 why it's valid) Author: Gal Lalouche - Technion 2015 © 17 public Monad plus(Monad other) { return this == empty ? other : this; }

Additive Monads (Cont.) If you think of empy as 0, plus as +, and flatMap as ×, 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.) Sometimes (Distributive law): 6.(m1.plus(m2)).flatMap(m3) ===(m1.flatMap(m3)).plus(m2.flatMap(m3)) Author: Gal Lalouche - Technion 2015 © 18

Additive Monads – Why? We can implement filter using empty : We can implement “ sum ” with plus : Author: Gal Lalouche - Technion 2015 © 19 public Monad filter(Predicate p) { return flatMap(t -> p.test(t) ? of(t) : empty); } public Monad sum(Predicate p) { Monad $ = empty; foreach(t -> $ = $.plus(t)); return$; }

Further Reading matter/ (Language Agnostic / Haskellish) matter/ (Haskell) (Haskell) (Scala) (Java) Author: Gal Lalouche - Technion 2015 © 20