Pattern Matching.

Slides:



Advertisements
Similar presentations
Expressions and Statements. 2 Contents Side effects: expressions and statements Expression notations Expression evaluation orders Conditional statements.
Advertisements

SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
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.
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.
Programming in Scala Chapters 2 & 3. Two “Hello World” programs package hello object HelloWorld1 extends Application { println("Hello, world 1!") } package.
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.
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.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 4 Making Decisions.
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.
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.
Chapter Making Decisions 4. Relational Operators 4.1.
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.
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.
Python Let’s get started!.
Classes and Objects and Traits And Other Miscellany 25-Jan-16.
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
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.
PHP LANGUAGE MULTIPLE CHOICE QUESTION SET-5
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
Chapter 4 The If…Then Statement
Python Let’s get started!.
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
Getting Functional.
Exceptions and other things
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 4: Making Decisions.
Variables, Printing and if-statements
Exceptions & exception handling
Exceptions & exception handling
null, true, and false are also reserved.
Functions As Objects.
TIPS: How to Be Successful
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Lecture 16 - Interfaces Professor Adams.
Cases and Classes and Case Classes
Topics 4.1 Relational Operators 4.2 The if Statement
CISC124 Labs start this week in JEFF 155. Fall 2018
The Java switch Statement
CMPE212 – Reminders The other four assignments are now posted.
The Scala API.
Seating “chart” Front Back 4 rows 5 rows 5 rows 4 rows 2 rows 2 rows
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Classes and Objects and Traits
CSC 143 Java Errors and Exceptions.
Unit 3: Variables in Java
Problem 1 Given n, calculate 2n
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

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

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

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

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 = Person@234bb715 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!" | } <console>:14: error: not found: value Person

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!

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: http://www.tutorialspoint.com/scala/scala_exception_handling.htm

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 (_ < 30)) match { | case None => "Everyone is passing" | case Some(n) => n + " isn't very good" | } res2: String = Everyone is passing

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)

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

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 0 => 1 | case n => n * factorial(n - 1) | } factorial: Int => Int = <function1>= 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)

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

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

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)

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 = Woman@12efc0ee scala> p match { | case m: Man => "male" | case f: Woman => "female" | } <console>:12: warning: match may not be exhaustive. It would fail on the following inputs: Child(), Person() p match { ^ res5: String = female

@ and _* In pattern matching, val @ 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 a @ List(b @ _, c @ _*) => s"After $b in $a comes $c" | } res7: String = After 1 in List(1, 2, 3, 4, 5) comes List(2, 3, 4, 5)

The End