Racket Pattern Matching

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

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

COP4020 Programming Assignment 1 - Spring 2011

Deferred operations. Continuations Structure and Interpretation of Computer Programs. Tail recursion in action.

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

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

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

YOUR NAME PLEASE: *** SOLUTIONS ***

An introduction to Scheme

Lisp. Versions of LISP

Documentation for LISP in BASIC

Syntactic Sugar: Using the Metacircular Evaluator to Implement the Language You Want

Functional Programming. Pure Functional Languages

Macros & Streams Spring 2018 Discussion 9: April 11, Macros

CSE 341 Section Handout #6 Cheat Sheet

The Design Recipe Fall 2018

Intro. Scheme Basics. scm> 5 5. scm>

The Design Recipe Fall 2017

From Syntactic Sugar to the Syntactic Meth Lab:

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

Fall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

Repetition Through Recursion

Functional programming with Common Lisp

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

CS450 - Structure of Higher Level Languages

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

CSE 341 Section 7. Eric Mullen Spring Adapted from slides by Nicholas Shahan, Dan Grossman, and Tam Dang

CS 314 Principles of Programming Languages

Scheme as implemented by Racket

CSCI 2041: Pattern Matching Basics


SCHEME AND CALCULATOR 5b

Using Symbols in Expressions (1) evaluate sub-expressions... Number. ( ) machine code to add

Essentials of Programming Languages Language

An Introduction to Scheme

CS1102: Macros and Recursion

Essentials of Programming Languages Language

CS61A Summer 2010 George Wang, Jonathan Kotker, Seshadri Mahalingam, Eric Tzeng, Steven Tang

Streams and Evalutation Strategies

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

CS 314 Principles of Programming Languages. Lecture 16

MIT Scheme Reference Manual

Warm-up! CS 3 Final Review. Predict the output. Predict the Output. Predict the output. Predict the output. What is your favorite color?

Programming Languages: Application and Interpretation

Scheme: Expressions & Procedures

ormap, andmap, and filter

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Introduction to Functional Programming

Module 8: Local and functional abstraction

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

CS 314 Principles of Programming Languages

Programming Languages: Application and Interpretation

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

Functional Programming. Pure Functional Languages

CSE 341 Section 7. Ethan Shea Autumn Adapted from slides by Nicholas Shahan, Dan Grossman, Tam Dang, and Eric Mullen

Organization of Programming Languages CS3200/5200N. Lecture 11

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

CSE 413 Midterm, May 6, 2011 Sample Solution Page 1 of 8

Homework 6: Higher-Order Procedures Due: 11:59 PM, Oct 16, 2018

Racket: Macros. Advanced Functional Programming. Jean-Noël Monette. November 2013

CSC 533: Programming Languages. Spring 2015

Building a system for symbolic differentiation

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

Racket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example.

CSE413 Midterm. Question Max Points Total 100

6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter

Pattern Matching for Scheme

Outline. Data Definitions and Templates Syntax and Semantics Defensive Programming

Introduction to Functional Programming in Racket. CS 550 Programming Languages Jeremy Johnson

Functional Programming

CS3: Introduction to Symbolic Programming. Lecture 14: Lists.

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5

Concepts of programming languages

CS61A Midterm 2 Review (v1.1)

Chapter 1. Fundamentals of Higher Order Programming

How to Design Programs Languages

CS 415 Midterm Exam Fall 2003

Functional Programming. Pure Functional Programming

Racket: Modules, Contracts, Languages

CS 61A Discussion 8: Scheme. March 23, 2017

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

Logic-Oriented Programming (5/11/2004)

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

Programming Paradigms

Lists of Lists. CS 5010 Program Design Paradigms Bootcamp Lesson 5.3

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

Scheme Quick Reference

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction

Shell CSCE 314 TAMU. Haskell Functions

Transcription:

Racket Pattern Matching Principles of Programming Languages https://lambda.mines.edu

if evaluates a predicate, and returns either the consequent or the alternative depending on the result: (if predicate consequent alternative) Example: (printf "n is ~a~%" (if (even? n) "even" "odd"))

The let macro will bind local variables: (let ([a 10] [b 20]) (printf "~a ~a~%" a b)) let* will bind in order, equivalent to nesting a bunch of lets together: (let* ([a 10] [b (+ a 10)]) (printf "~a ~a~%" a b)) Equivalent to: (let ([a 10]) (let ([b (+ a 10)]) (printf "~a ~a~%" a b)))

cond takes a series of clauses. You can think of it as replacing a big long if chain: (cond [predicate-1 consequent-1] [predicate-2 consequent-2]... [predicate-n consequent-n] [else alternative]) Equivalent to: (if predicate-1 consequent-1 (if predicate-2 consequent-2... (if predicate-n consequent-n alternative)))

(printf "Your BMI rating is: ~a~%" (cond [(< bmi 18.5) "underweight"] [(< bmi 24.9) "normal"] [(< bmi 29.9) "overweight"] [else "obese"]))

Case evaluates and returns the clause which has a quoted form equal? to the value passed. (case value [(a-1 a-2... a-n) result-1] [(b-1 b-2... b-n) result-2]... [else result]) Careful Parenthesis are needed around the values in each clause, even if there is only one value to match.

(define (pet-classification pet-type) (case pet-type [(cat dog fish) 'normal] [(mouse rat ferret) 'strange] [(zebra gorilla elephant) 'not-a-pet] [else 'unknown])) > (pet-classification 'cat) 'normal > (pet-classification 'ferret) 'strange > (pet-classification 'gorilla) 'not-a-pet > (pet-classification 'horse) 'unknown

(define (login-as username password) (case (list username password) [(("bob" "secret") ("jill" "ihatebob")) "Welcome!"] [(("badguy" "badguy")) "Not authorized!"] [else "Unknown username or password"])) > (login-as "jill" "ihatebob") "Welcome!" > (login-as "jill" "ih8bob") "Unknown username or password" > (login-as "badguy" "badguy") "Not authorized!"

;; Note: this algorithm is not efficent (define (fib n) (case n [(0 1) n] [else (+ (fib (- n 1)) (fib (- n 2)))]))

With your learning group, choose whether to implement each of these functions using either case or cond. Then, once you have decided, write an implementation: 1 A function, which, when passed an even number, divides it by two. When the function is passed an odd number, it will multiply it by three then add 1. If the function is passed anything else (e.g., a string), it will return "oh noes!". 2 A function f of parameter n which returns 'magic when passed 0, 10, 20, or 30, or (f (floor (/ n 2))) otherwise.

What if we could combine the functionality of let, cond, and case (and even more) all into a single syntax? Racket has this: it s called match!

Here is the basic syntax for match: (match value [pattern-1 result-1] [pattern-2 result-2]... [pattern-n result-n]) Each of these patterns is a very special syntax form which Racket will use to determine if there is a match, as well as bind variable names inside of the body of the clause.

Simple constants will match when they are equivalent: (match user-input ["true" #t] ["false" #f]) Underscore can be used to match anything: (match user-input ["true" #t] ["false" #f] [_ (error "Not a valid input")])

If a variable name is used in a pattern, racket will bind what matches to that name: (match (+ a b c) [10 "it's 10!"] [the-number (format "sadly, only ~a..." the-number)])

The pattern (? predicate-function optional-binding) can be used to test if predicate-function returns #t when called on the value. (match (+ a b c) [(? odd?) "How odd..."] [(? even? x) (format "~a is even!" x)])

The pattern (list...) contains patterns and matches a list whose elements match the patterns in order. (match some-list [(list) "that list is empty!"] [(list a) (format "the list has a single element: ~a" a)] [(list a (? even? b)) (format "~a and ~a, second is even" a [_ "something else"])

Repeating a variable name will not only bind the value to the variable, but actually check that the elements are equal? too! (match some-list [(list (? even? a) a) "two even equivalent elements"] [(list a a) "two elements, the same"] [(list a b) "two elements, different"] [_ "something else"])

The (list-rest a b... z z-cdr) pattern can be used to match the elements of a list and dump the rest of the elements in z-cdr. For example: (match some-list [(list) "empty list"] [(list _) "one element"] [(list-rest _ tail) tail])

Consider the following function which sums the elements of a list: (define (sum-list lst) (match lst [(list) 0] [(list-rest head tail) (+ head (sum-list tail))]))

Quasiquoted patterns match lists of matching symbols, with commas escaping the quotation (and can be any pattern): (define (extract-value lst) (match lst [`(sally,x,_) x] [`(mary,_,y) y])) Like,@ splices in a list to a quasiquotation, when used in a pattern, it will extract a pattern matching from the list: (define (extract-rest lst) (match lst [`(sally,@(list-rest x)) x]))

match is used to match the arguments of a function so often, that Racket provides a syntax for putting a syntax right inside of define. Example: ;; Return the first n elements of a list (define/match (take n lst) [(0 _) '()] [(_ (list-rest head tail)) (cons head (take (- n 1) tail))])

With your learning group, write a function using define/match which drops the first n elements of a list: > (drop 3 '(1 2 3 4)) '(4) > (drop 1 '(7)) '() > (drop 0 '(8 4 1 4)) '(8 4 1 4) > (drop 0 '()) '() ;; OK if error when n is greater than the list length, e.g., ;; (drop 1 '())