Patterns in OCaml functions. Formal vs. actual parameters Here's a function definition (in C): –int add (int x, int y) { return x + y; } –x and y are.

Slides:



Advertisements
Similar presentations
Functional Programming Lecture 10 - type checking.
Advertisements

Modern Programming Languages, 2nd ed.
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
Higher-order functions in OCaml. Higher-order functions A first-order function is one whose parameters and result are all "data" A second-order function.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
Writing functions in OCaml. Defining a simple function # let add (x, y) = x + y;; val add : int * int -> int = Notice what this says: –add is a value.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Patterns in ML functions. Formal vs. actual parameters Here's a function definition (in C): –int add (int x, int y) { return x + y; } –x and y are the.
Functional Programming Universitatea Politehnica Bucuresti Adina Magda Florea
CSE341: Programming Languages Lecture 5 Pattern-Matching Dan Grossman Fall 2011.
Lecture 3: Topics If-then-else Operator precedence While loops Static methods Recursion.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
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.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
1 Functional languages (e.g. Scheme, ML) Scheme is a functional language. Scheme is based on lambda calculus. lambda abstraction = function definition.
28-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
Type Inference: CIS Seminar, 11/3/2009 Type inference: Inside the Type Checker. A presentation by: Daniel Tuck.
CSE 341 : Programming Languages Lecture 6 Fancy Patterns, Exceptions, Tail Recursion Zach Tatlock Spring 2014.
Haskell Chapter 3, Part I. Pattern Matching  Pattern matching with tuples  Pattern matching with list comprehensions  As-patterns.
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.
OCaml The PL for the discerning hacker.. Hello. I’m Zach, one of Sorin’s students.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
COP4020 Programming Languages Functional Programming Prof. Xin Yuan.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
Types in programming languages1 What are types, and why do we need them?
CSE 341 : Programming Languages Lecture 2 Functions, Pairs, Lists Zach Tatlock Spring 2014.
12/9/20151 Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC Based in part on slides by Mattox.
CMSC 330: Organization of Programming Languages Operational Semantics a.k.a. “WTF is Project 4, Part 3?”
Introduction to Objective Caml. General comments ML is a purely functional language--there are (almost) no side effects There are two basic dialects of.
Chapter SevenModern Programming Languages1 A Second Look At ML.
CS412/413 Introduction to Compilers Radu Rugina Lecture 13 : Static Semantics 18 Feb 02.
CSED101 INTRODUCTION TO COMPUTING SUM TYPE 유환조 Hwanjo Yu.
CSED101 INTRODUCTION TO COMPUTING FUNCTION ( 함수 ) 유환조 Hwanjo Yu.
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
CMSC 330: Organization of Programming Languages Operational Semantics.
3/8/20161 Programming Languages and Compilers (CS 421) Reza Zamani Based in part on slides by Mattox Beckman, as updated.
Cs776(Prasad)L6sml971 SML-97 Specifics SML/NJ 110.
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
Basic Data Types & Memory & Representation. Basic data types Primitive data types are similar to JAVA: char int short long float double Unlike in JAVA,
CSE-321 Programming Languages Introduction to Functional Programming POSTECH March 8, 2006 박성우.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
CMSC 330: Organization of Programming Languages Object Oriented Programming with OCaml.
Programming Languages and Compilers (CS 421)
User-Written Functions
ML: a quasi-functional language with strong typing
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Spring 2017.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
FP Foundations, Scheme In Text: Chapter 14.
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Spring 2013.
CSE 341 Section 2 Winter 2018 Adapted from slides by Nick Mooney, Nicholas Shahan, Patrick Larson, and Dan Grossman.
CSE 341 Section 5 Winter 2018.
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Autumn 2018.
CSE-321 Programming Languages Introduction to Functional Programming
CSE 341 Section 2 Nick Mooney Spring 2017
CSE-321 Programming Languages Introduction to Functional Programming
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Zach Tatlock Winter 2018.
Function.
Java Programming Language
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Spring 2019.
Function.
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Autumn 2017.
Presentation transcript:

Patterns in OCaml functions

Formal vs. actual parameters Here's a function definition (in C): –int add (int x, int y) { return x + y; } –x and y are the formal parameters –Formal parameters must be variables (in C) Here's a function call: –total = add (total, 5); –total and 5 are the actual parameters –Actual parameters typically can be expressions

Parameters are patterns In most conventional languages, formal parameters must be variables –Example: x and y in f(x, y) are both variables In OCaml, all functions take a single parameter For example, in let add (x, y) = x + y;; we say that (x, y) is one parameter, a tuple But (x, y) is not a variable......it is a pattern

The unit as parameter Consider: let five ( ) = 5;; The single parameter is the unit, ( ) But the unit is a value, that is, a constant In OCaml, a formal parameter (not just an actual parameter) may be a constant Parameter transmission uses pattern matching

Patterns separate cases in Prolog Prolog passes parameters by unification Unification is a very general and powerful kind of pattern matching Parameters are used to separate a task into cases, for example, –member(X, [X | _]). member(X, [_ | Y]) :- member(X, Y).

Patterns separate cases in Java Java doesn't do pattern matching on parameters, but... Java does allow methods to be overloaded Overloaded methods have different signatures –The signature describes the number and type of parameters This is a primitive kind of pattern matching In a sense, it separates method calls into cases

OCaml allows multiple patterns Pattern matching is not guaranteed to succeed It's OK if a Prolog predicate fails, but......an OCaml function must return a value Therefore, OCaml must support multiple patterns in a function definition Also, OCaml must ensure that the patterns are exhaustive, i.e. some pattern must match

Matchs A match consists of rules separated by | A rule has the form pattern -> result –pattern1 -> result1 | pattern2 -> result2 |... patternN -> resultN The results must all be of the same type The patterns should be exhaustive A "match" is not a complete expression by itself

match expressions A match all by itself isn't a complete expression A match expression has the form: match expression with match Patterns are tried in the order they are given When a match is found, the corresponding result is evaluated and returned as the result If nothing matches, a Match_failure exception is raised We haven't covered exceptions yet

The match expression # match 'b' with 'a' -> 1 | 'b' -> 2 | 'c' -> 3;; – Characters 0-47: Warning: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: 'd' - : int = 2

Using match in a function # let rec fact n = match n with 0 -> 1 | n -> fact (n - 1) + fact (n - 2);; – val fact : int -> int = Note: rec is required for recursive functions If you try this, use Enter on the numeric pad!

Functions with multiple patterns # let rec factorial = function 0 -> 1 | n -> n * factorial (n - 1);; Notice: –The word function replaces the use of match –There is no explicit formal parameter –Names in patterns are used instead of parameters

Lists as patterns Use the cons operator :: to form patterns The pattern (x :: xs) matches a nonempty list # let rec listSize = function [] -> 0 | (x::xs) -> 1 + listSize xs;; val listSize : 'a list -> int = # listSize ['a'; 'b'; 'c'];; - : int = 3

Exhaustive patterns # let car = function (x::xs) -> x;; Characters 10-31: Warning: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: [ ] val car : 'a list -> 'a = # car ['a'; 'b'; 'c'];; - : char = 'a' OCaml warns you but lets you continue

Last element of a list # let rec last = function [x] -> x | (x::xs) -> last xs;; –Characters 15-53: Warning: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: [ ] val last : 'a list -> 'a = # last ["one"; "two"; "three"];; - : string = "three" Notice the use of [x] and (x::xs) as patterns

Doubling each element of a list # let rec doubleAll = function [ ] -> [ ] | (x::xs) -> (2 * x) :: doubleAll xs;; val doubleAll : int list -> int list = # doubleAll [1; 2; 3; 4; 5];; - : int list = [2; 4; 6; 8; 10]

if...then...else... expressions if expr1 then expr2 else expr3 is actually syntactic sugar for match expr1 with true => expr2 | false => expr3 If you make an error in an if expression, some compilers may report it as an error in a match expression

OCaml is purely functional The if and case expressions are special cases of a match; so is fun Arithmetic operators such as + are syntactic sugar for functions –Operators can be used as functions: op + (a, b) In OCaml, "expressions" are really functions, and basically everything is a function

The End