Case by Case. Chapter 3

Similar documents
Names and Functions. Chapter 2

Plan (next 4 weeks) 1. Fast forward. 2. Rewind. 3. Slow motion. Rapid introduction to what s in OCaml. Go over the pieces individually

Logical Operators and switch

Functional Programming and Haskell

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Chapter 15. Functional Programming. Topics. Currying. Currying: example. Currying: example. Reduction

OCaml. History, Variants. ML s holy trinity. Interacting with ML. Base type: Integers. Base type: Strings. *Notes from Sorin Lerner at UCSD*

CMSC 330: Organization of Programming Languages. Operational Semantics

Introduction to OCaml

COP 4516: Math for Programming Contest Notes

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

3.7 Denotational Semantics

Recursion. CSCI 112: Programming in C

CS 320: Concepts of Programming Languages

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #06 Loops: Operators

Programming Languages and Compilers (CS 421)

Answers to Questions. Chapter 1 (Starting Off)

CS 320: Concepts of Programming Languages

Problem Set CVO 103, Spring 2018

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics

Homework 8: Matrices Due: 11:59 PM, Oct 30, 2018

Types, Expressions, and States

Language Proposal: tail

Haskell Programs. Haskell Fundamentals. What are Types? Some Very Basic Types. Types are very important in Haskell:

A general introduction to Functional Programming using Haskell

ML 4 A Lexer for OCaml s Type System

CS 4110 Programming Languages & Logics. Lecture 17 Programming in the λ-calculus

Grammar Rules in Prolog!!

CpSc 421 Final Solutions

Any questions. Say hello to OCaml. Say hello to OCaml. Why readability matters. History, Variants. Plan (next 4 weeks)

Programming Languages

Conditionals !

Functional Programming. Lecture 2: Algebra

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

Typed Racket: Racket with Static Types

Homework 3: Recursion Due: 11:59 PM, Sep 25, 2018

ECE 2574: Data Structures and Algorithms - Recursion Part I. C. L. Wyatt

APCS Semester #1 Final Exam Practice Problems

This assignment has four parts. You should write your solution to each part in a separate file:

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Introduction to Objective Caml

List Functions, and Higher-Order Functions

Introduction to Functional Programming in OCaml

CS 440: Programming Languages and Translators, Spring 2019 Mon

Programming Language Concepts: Lecture 14

CS 11 Haskell track: lecture 1

So what does studying PL buy me?

REVIEW. The C++ Programming Language. CS 151 Review #2

Basic data types. Building blocks of computation

Semantics of programming languages

Functions BCA-105. Few Facts About Functions:

Programming Languages and Techniques (CIS120)

Lecture #23: Conversion and Type Inference

Coding Standards for Java

CS 421, Fall Sample Final Questions & Solutions

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Thinking Induc,vely. COS 326 David Walker Princeton University

CMSC 330: Organization of Programming Languages. OCaml Expressions and Functions

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

What is recursion? Recursion. How can a function call itself? Recursive message() modified. contains a reference to itself. Week 7. Gaddis:

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

RECURSION: n. SEE RECURSION 3

CMSC 330, Fall 2013, Practice Problems 3

LECTURE 16. Functional Programming

Lab 10: OCaml sequences, comparators, stable sorting 12:00 PM, Nov 12, 2017

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

CMSC 330, Fall 2013, Practice Problem 3 Solutions

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages

def F a c t o r i a l ( n ) : i f n == 1 : return 1 else : return n F a c t o r i a l ( n 1) def main ( ) : print ( F a c t o r i a l ( 4 ) )

COMPSCI 230 Discrete Math Prime Numbers January 24, / 15

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Decisions in Java IF Statements

Functional Programming. Introduction To Cool

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

Lecture 2: The Basis of SML

CS /534 Compiler Construction University of Massachusetts Lowell. NOTHING: A Language for Practice Implementation

ML 4 Unification Algorithm

Register Machines. Connecting evaluators to low level machine code

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

List Processing in Ocaml

Assignment 0. Computer Science 52. Due Friday, September 7, 2018, at 5:00 pm

Background. CMSC 330: Organization of Programming Languages. Useful Information on OCaml language. Dialects of ML. ML (Meta Language) Standard ML

Programming Languages

Information Science 1

Why OCaml? Introduction to Objective Caml. Features of OCaml. Applications written in OCaml. Stefan Wehr

Programming Lecture 3

CMSC330 Fall 2016 Midterm #1 2:00pm/3:30pm

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

Lab 7: OCaml 12:00 PM, Oct 22, 2017

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Introduction. Chapter 1

Begin at the beginning

FUNCTIONAL PROGRAMMING 1 HASKELL BASICS

Transcription:

Chapter 3 Case by Case In the previous chapter, we used the conditional expression if... then... else to define functions whose results depend on their arguments. For some of them we had to nest the conditional expressions one inside another. Programs like this are not terribly easy to read, and expand quickly in size and complexity as the number of cases increases. OCaml has a nicer way of expressing choices pattern matching. For example, recall our factorial function: factorial : let rec factorial a = if a = 1 then 1 else a * factorial (a - 1) We can rewrite this using pattern matching: factorial : let rec factorial a = match a with 1 -> 1 _ -> a * factorial (a - 1) We can read this as See if a matches the pattern 1. If it does, just return 1. If not, see if it matches the pattern _. If it does, the result is a * factorial (a - 1). The pattern _ is special it matches anything. Remember our isvowel function from the previous chapter? c = 'a' c = 'e' c = 'i' c = 'o' c = 'u' 19

20 Chapter 3. Case by Case Here is how to write it using pattern matching: 'a' -> true 'e' -> true 'i' -> true 'o' -> true 'u' -> true _ -> false If we miss out one or more cases, OCaml will warn us: OCaml # 'a' -> true 'e' -> true 'i' -> true 'o' -> true 'u' -> true;; # Warning 8: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: 'b' val isvowel : char -> bool OCaml does not reject the program, because there may be legitimate reasons to miss cases out, but for now we will make sure all our pattern matches are complete. Notice that we had to repeat true five times. This would be awkward if the expression to be calculated was more complicated. We can combine patterns like this: 'a' 'e' 'i' 'o' 'u' -> true _ -> false Finally, let us rewrite Euclid s Algorithm from the previous chapter: gcd : let rec gcd a b = if b = 0 then a else gcd b (a mod b)

Chapter 3. Case by Case 21 Now in pattern matching style: gcd : let rec gcd a b = match b with 0 -> a _ -> gcd b (a mod b) The type of a whole match... with... expression is determined by the types of the expressions on the right hand side of each -> arrow, all of which must be alike: {}}{ {}}{ gcd b (a mod b) match b with 0 -> } a _ -> {{ } We use pattern matching whenever it is easier to read and understand than if... then... else expressions.

22 Chapter 3. Case by Case Questions 1. Rewrite the not function from the previous chapter in pattern matching style. 2. Use pattern matching to write a recursive function which, given a positive eger n, returns the sum of all the egers from 1 to n. 3. Use pattern matching to write a function which, given two numbers x and n, computes x n. 4. For each of the previous three questions, comment on whether you think it is easier to read the function with or without pattern matching. How might you expect this to change if the functions were much larger? 5. What does match 1 + 1 with 2 -> match 2 + 2 with 3 -> 4 4 -> 5 evaluate to? 6. There is a special pattern x..y to denote continuous ranges of characters, for example 'a'..'z' will match all lowercase letters. Write functions islower and isupper, each of type char bool, to decide on the case of a given letter.

So Far 1Integers min_... -3-2 -1 0 1 2 3... max_ of type. Booleans true and false of type bool. Characters of type char like 'X' and '!'. Mathematical operators + - * / mod which take two egers and give another. Operators = < <= > >= <> which compare two values and evaluate to either true or false. The conditional if expression1 then expression2 else expression3, where expresssion1 has type bool and expression2 and expression3 have the same type as one another. The boolean operators && and which allow us to build compound boolean expressions. 2Assigning a name to the result of evaluating an expression using the let name = expression construct. Building compound expressions using let name1 = expression1 in let name2 = expression2 in... Functions, roduced by let name argument1 argument2... = expression. These have type α β, α β γ etc. for some types α, β, γ etc. Recursive functions, which are roduced in the same way, but using let rec instead of let. 3 Matching patterns using match expression1 with pattern1... -> expression2 pattern2... -> expression3... The expressions expression2, expression3 etc. must have the same type as one another, and this is the type of the whole match... with expression.