Pattern Matching. The match statement C and Java have a switch statement which uses a small integer value to choose among alternatives In Java 7, it is.

Slides:



Advertisements
Similar presentations
Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Advertisements

Expressions and Statements. 2 Contents Side effects: expressions and statements Expression notations Expression evaluation orders Conditional statements.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
CIT 590 Intro to Programming Java lecture 3. Hashmaps The equivalent of python dictionaries. With both ArrayLists and Hashmaps, the syntax only allows.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 4 Making.
Programming in Scala Chapters 2 & 3. Two “Hello World” programs package hello object HelloWorld1 extends Application { println("Hello, world 1!") } package.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Python Control of Flow.
Java. Why Java? It’s the current “hot” language It’s almost entirely object-oriented It has a vast library of predefined objects It’s platform independent.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
17-Sep-15 Erlang. Running Erlang Double-click on the Erlang icon, or type erl into a terminal (cmd) window You can try short pieces of code from here,
Pattern matching. The if expression The else part of an if expression is optional if ( condition ) expression1 else expression2 If the condition evaluates.
COIT29222 Structured Programming Slide 1 COIT29222-Structured Programming Lecture Week 06  Reading: Study Guide Book 2, Modules 9 & 10 Textbook (4 th.
Chapter 6: Functions Starting Out with C++ Early Objects
Exceptions Handling Exceptionally Sticky Problems.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 4 Making Decisions.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Functions and Methods. Definitions and types A function is a piece of code that takes arguments and returns a result A pure function is a function whose.
Basic Java Syntax COMP 401, Spring 2014 Lecture 2 1/14/2014.
Exceptions, cont’d. Factory Design Pattern COMP 401 Fall 2014 Lecture 12 9/30/2014.
Copyright Curt Hill Variables What are they? Why do we need them?
The Scala API. Scala has a reputation of being a difficult language Some people feel that Scala is beyond what the average programmer can master Others.
Cases and Classes and Case Classes And Other Miscellany 16-Dec-15.
Decisions. Three Forms of Decision Making in Java if statements (test a boolean expression) switch statements (test an integer expression) conditional.
Copyright Curt Hill The C/C++ switch Statement A multi-path decision statement.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Advanced Arithmetic, Conditionals, and Loops INFSY 535.
Exceptions and Assertions Chapter 15 – CSCI 1302.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Python Let’s get started!.
CIT 590 Intro to Programming Lecture 13. Some Eclipse shortcuts CTRL + SHIFT + F – format file (proper indentation etc). Please do this before you submit.
Classes and Objects and Traits And Other Miscellany 25-Jan-16.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
COMP Loop Statements Yi Hong May 21, 2015.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
JavaScript and Ajax (Control Structures) Week 4 Web site:
Sequences and for loops. Simple for loops A for loop is used to do something with every element of a sequence scala> for (i
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Introduction to Exceptions in Java CS201, SW Development Methods.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Selection (also known as Branching) Jumail Bin Taliba by
Class Structure 15-Jun-18.
Selections Java.
Chapter 4: Making Decisions.
Classes and Objects and Traits
Exceptions and other things
Functions As Objects.
Pattern Matching.
Cases and Classes and Case Classes
Lecture Notes – Week 2 Lecture-2
The Java switch Statement
Seating “chart” Front Back 4 rows 5 rows 5 rows 4 rows 2 rows 2 rows
Classes and Objects and Traits
CSC 143 Java Errors and Exceptions.
Presentation transcript:

Pattern Matching

The match statement C and Java have a switch statement which uses a small integer value to choose among alternatives In Java 7, it is now possible to use switch with Strings switch is rarely used in Java programs The Scala “equivalent” is the match expression scala> val n = 4 n: Int = 4 scala> n match { | case 1 => "one" | case 2 => "two" | case _ => "many" | } res0: String = many 2

Matching on values scala> object Obj defined module Obj scala> val d = 5.0 d: Double = 5.0 scala> val lst = List(1, 2, 3) lst: List[Int] = List(1, 2, 3) scala> def valMatch(x: Any) = x match { | case 5 => println("Int") | case 5.0 => println("Double") | case "abc" => println("String") | case List(1, 2, 3) => println("List") | case Obj => println("User-defined Obj") | case _ => println("None of the above") | } valMatch: (x: Any)Unit scala> valMatch(5) Int scala> valMatch(Obj) User-defined Obj scala> valMatch("abc") String 3

Matching on types scala> def whatKind(x: Any) = x match { | case s: String => s"This is the string [$s]" | case d: Double => s"$d is a Double" | case i: Int => s"$i is an Int" | case x => s"I don't know what $x is" | } whatKind: (x: Any)String scala> whatKind(5.0) res3: String = 5.0 is a Double scala> whatKind(List(1, 2, 3)) res4: String = I don't know what List(1, 2, 3) is 4

Matching with guards scala> def oddOrEven(n: Any) = n match { | case n: Int if n % 2 == 0 => "Even integer" | case n: Int => "Odd integer" | case x => x + " is something else" | } oddOrEven: (n: Any)String scala> oddOrEven(5) res18: String = Odd integer scala> oddOrEven(6) res19: String = Even integer scala> oddOrEven(7.0) res20: String = 7.0 is something else 5

Matching on user-defined types For user-defined classes, you can match on the type scala> class Person(val name: String) defined class Person scala> val dave = new Person("Dave") dave: Person = scala> dave match { | case n: Person => "ok" | case _ => "nope!" | } res2: String = ok But you can’t match on the particular object of a plain (non-case) class scala> dave match { | case Person("Dave") => "ok" | case _ => "nope!" | } :14: error: not found: value Person 6

Matching on objects of case classes scala> val dave = new Person("Dave") dave: Person = Person(Dave) scala> val beth = new Person("Beth") beth: Person = Person(Beth) scala> def sayHi(p: Person) = p match { | case Person("Dave") => "Oh, it's just Dave." | case Person(name) => s"Hi, $name!" | } sayHi: (p: Person)String scala> sayHi(dave) res7: String = Oh, it's just Dave. scala> sayHi(beth) res8: String = Hi, Beth! 7

Matching on exceptions Scala’s try-catch-finally is similar to Java’s, but the catch clauses are case expressions try { val f = new FileReader("input.txt") } catch { case ex: FileNotFoundException => { println("Missing file exception") } case ex: IOException => { println("IO Exception") } } finally { println("Exiting finally...") } Source: 8

Matching on optional values The Option type is used frequently in Scala Scala’s None is used in places where Java might use null scala> val scores = List(78, 43, 82, 67, 55) scores: List[Int] = List(78, 43, 82, 67, 55) scala> scores find (_ > 90) res0: Option[Int] = None scala> scores find (_ < 70) res1: Option[Int] = Some(43) scala> (scores find (_ "Everyone is passing" | case Some(n) => n + " isn't very good" | } res2: String = Everyone is passing 9

Matching in assignments scala> val jean = new Person("Jean", 23) jean: Person = Person(Jean,23) scala> jean match { | case Person(n, a) => s"$n is $a years old" | } res5: String = Jean is 23 years old scala> val Person(n, a) = jean n: String = Jean a: Int = 23 scala> val list = List(1, 2, 3, 4, 5) list: List[Int] = List(1, 2, 3, 4, 5) scala> val h :: hh :: t = list h: Int = 1 hh: Int = 2 t: List[Int] = List(3, 4, 5) 10

Matching in for expressions scala> val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo") capitals: scala.collection.immutable.Map[String,String] = Map(France -> Paris, Japan -> Tokyo) scala> for ((country, city) <- capitals) { | println(s"The capital of $country is $city.") | } The capital of France is Paris. The capital of Japan is Tokyo. Values that don’t match are simply filtered out scala> val scores = List(("John", 90), ("Mary", 100), ("Bill", 95), ("Jane", 100)) scores: List[(String, Int)] = List((John,90), (Mary,100), (Bill,95), (Jane,100)) scala> for ((name, 100) <- scores) println(name) Mary Jane 11

Patterns as partial functions A sequence of cases is a partial function, and may be used anywhere a function literal may be used scala> val factorial: Int => Int = { | case 1 => 1 | case n => n * factorial(n - 1) | } factorial: Int => Int = = scala> factorial(5) res14: Int = 120 scala> (1 to 10) map { | case n if n % 2 == 0 => n / 2 | case n => 3 * n + 1 | } res16: scala.collection.immutable.IndexedSeq[Int] = Vector(4, 1, 10, 2, 16, 3, 22, 4, 28, 5) 12

Failing to match It’s an error if no case in a pattern match is satisfied There are two basic choices for the last case: case _ will match anything, and you don’t care what case variable will match anything, and you can use the value of the variable in the body of the case 13

isDefinedAt A Map is a partial function from keys to values The method isDefinedAt determines whether a partial function is defined for a particular input value scala> val scores = List(("John", 90), ("Mary", 100), ("Bill", 95), ("Jane", 100)) scores: List[(String, Int)] = List((John,90), (Mary,100), (Bill,95), (Jane,100)) scala> val mapScores = scores.toMap mapScores: scala.collection.immutable.Map[String,Int] = Map(John -> 90, Mary -> 100, Bill -> 95, Jane -> 100) scala> mapScores.isDefinedAt("William") res1: Boolean = false scala> mapScores.isDefinedAt("Bill") res2: Boolean = true 14

collect collect is a partial function that takes an iterator and returns a new iterator over only defined values def collect[B](pf: PartialFunction[A, B]): Iterator[B] scala> val scores = Map(("John", 90), ("Mary", 100), ("Bill", 95), ("Jane", 100)) scores: scala.collection.immutable.Map[String,Int] = Map(John -> 90, Mary -> 100, Bill -> 95, Jane -> 100) scala> val names = List("John", "Frank", "Jane", "Joe") names: List[String] = List(John, Frank, Jane, Joe) scala> names collect scores res10: List[Int] = List(90, 100) 15

Sealed classes A class is sealed if (1) it is declared with the keyword sealed, and (2) all subclasses are declared on the same file This allows Scala to check for missing cases scala> sealed class Person // omitting responses to save space scala> class Man extends Person scala> class Woman extends Person scala> class Child extends Person scala> val p: Person = new Woman p: Person = scala> p match { | case m: Man => "male" | case f: Woman => "female" | } :12: warning: match may not be exhaustive. It would fail on the following inputs: Child(), Person() p match { ^ res5: String = female 16

@ and _* In pattern matching, pattern_part captures the value of the pattern part in the value In matching a sequence, _* matches the remainder of the sequence scala> list match { | case _, _*) => s"After $b in $a comes $c" | } res7: String = After 1 in List(1, 2, 3, 4, 5) comes List(2, 3, 4, 5) 17

18 The End