Introduction to OCaml Slides prepared by Matt Gruskin Some material borrowed from the CIS 500 lecture notes.

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

Higher-Order Functions and Loops c. Kathi Fisler,
7-Jun-14 Lists. Arrays and Lists Arrays are a fixed length and occupy sequential locations in memory This makes random access (for example, getting the.
Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Higher-order functions in ML
Programovací jazyky F# a OCaml Chapter 4. Generic and recursive types.
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.
Container Types in Python
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.
F# Overview: Immutable Data + Pure Functions. Acknowledgements Authored by – Thomas Ball, MSR Redmond Includes content from the F# team.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
F28PL1 Programming Languages Lecture 14: Standard ML 4.
CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 8 Fruitful Functions 05/02/09 Python Mini-Course: Day 2 - Lesson 8 1.
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.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  ML lists are immutable.  Elements.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Map and Fold Building Powerful Abstractions. Hello. I’m Zach, one of Sorin’s students.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Recursion.
CSE341: Programming Languages Lecture 7 Functions Taking/Returning Functions Dan Grossman Fall 2011.
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.
Cse536 Functional Programming 1 7/14/2015 Lecture #2, Sept 29, 2004 Reading Assignments –Begin Chapter 2 of the Text Home work #1 can be found on the webpage,
Programovací jazyky F# a OCaml Chapter 5. Hiding recursion using function-as-values.
ISBN Chapter 15 Functional Programming Languages.
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.
Chapter 9: Functional Programming in a Typed Language.
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.
Chapter Fifteen: Functional Programming Languages Lesson 12.
Compiling Functional Programs Mooly Sagiv Chapter 7
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
CMSC 330: Organization of Programming Languages Maps and Folds Anonymous Functions.
CMSC 330: Organization of Programming Languages
Kyung-Goo Doh Hanyang University - ERICAComputer Science & Engineering Functional Programming / Imperative Programming CSE215 Fundamentals of Program Design.
Introduction to Objective Caml. General comments ML is a purely functional language--there are (almost) no side effects There are two basic dialects of.
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
1 Introduction to Functional Programming in Racket CS 270 Math Foundations of CS Jeremy Johnson.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
Functional Programming in Python Abhishek Dasgupta Indian Institute of Science Education and Research, Kolkata.
Functional Programming
Programming Languages and Compilers (CS 421)
ML: a quasi-functional language with strong typing
CSE 341 Lecture 5 efficiency issues; tail recursion; print
ML Again ( Chapter 7) Patterns Local variable definitions
Expanded Recursive Diagrams OCAML rapid tour, day 2
CMSC 330: Organization of Programming Languages
Introduction to Functional Programming in Racket
LECTURE 31: INTRO TO FUNCTIONAL PROGRAMMING
An aggregation mechanism
Objective caml Daniel Jackson MIT Lab for Computer Science 6898: Advanced Topics in Software Design March 18, 2002.
FP Foundations, Scheme In Text: Chapter 14.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
CSC1018F: Intermediate Python
Type & Typeclass Syntax in function
Functional Programming Languages
Introduction to Functional Programming in Racket
CSE 3302 Programming Languages
Madhusudan Parthasarathy
CISC101 Reminders Assignment 3 due today.
Functional Programming Languages
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
Review Previously in: Lots of language features: functions, lists, records, tuples, variants, pattern matching Today: No new language features New idioms.
Presentation transcript:

Introduction to OCaml Slides prepared by Matt Gruskin Some material borrowed from the CIS 500 lecture notes

Functional Programming Persistent (immutable) data structures –No assignments in pure functional programming! Recursion –No loops in pure functional programming! Higher-order functions –Functions that take other functions as arguments or return functions as results OCaml is not a pure functional language –OCaml does have for and while loops, but I won’t show them here

Let statements Give a name to an expression or define a function # let pi = ;; val pi : float = # pi;; -: float = # let circle_area r = pi *. r *. r;; val circle_area : float -> float = # circle_area 4.0;; - : float = >>> pi = ; >>> pi >>> def circle_area(r):... return pi * r * r;... >>> circle_area(4);

Syntax differences from Python Method calls –Parameters separated by spaces instead of commas… and no parentheses around parameter list –Python: method(a,b,c) –OCaml: method a b c

Type Inference Types are inferred (like Python) –So you don’t have to give parameters types Unlike Python, types are inferred BEFORE runtime –When entering a function in the toplevel you’ll see Param type -> param type -> … -> return type –This is why different operators are needed for different numeric types # let circle_area r = pi *. r *. r;; val circle_area : float -> float =

Lists Similar to lists in Python Unlike Python, implemented as linked lists Cons – hd :: tl (hd is first element, tl is a list) Unlike Python, lists are homogeneous –You can do [5,’a’,True] in Python but you can’t do [5;’a’;true] in OCaml # let l = [1;3;5;7];; val l : int list = [1; 3; 5; 7] # l;; - : int list = [1; 3; 5; 7] # l;; - : int list = [-1; 0; 1; 3; 5; 7] # List.hd l;; - : int = 1 # List.tl l;; -: int list = [3; 5; 7] # List.nth l 2;; - : int = 5 >>> l = [1,3,5,7] >>> l [1, 3, 5, 7] >>> [-1,0] + l [-1, 0, 1, 3, 5, 7] >>> l[0] 1 >>> l[1:] [3, 5, 7] >>> l[2] 5

Recursive functions let rec gcd a b = if a=0 then b else if a>b then gcd b a else gcd (b mod a) a let rec repeat k n = if n=0 then [] else k :: repeat k (n-1) # repeat 1 4;; - : int list = [1; 1; 1; 1] def gcd(a,b): if a == 0: return b if a > b: return gcd(b,a) return gcd(b % a, a) def repeat(k,n): if n == 0: return [] else: return [k] + repeat(k,n-1) >>> repeat(1,4) [1, 1, 1, 1]

Pattern Matching Alternative to imperative statements like if, switch let rec gcd a b = match a with 0 -> b | x when x > b -> gcd b a | _ -> gcd (b mod a) a let rec gcd a b = if a=0 then b else if a>b then gcd b a else gcd (b mod a) a

Tail Recursion let rec rev l = match l with [] -> [] | hd :: tl -> (rev [hd] let rec tailrev l r = match l with [] -> r | hd :: tl -> tailrev tl (hd :: r) let rec tailrev ?(r=[]) l = match l with [] -> r | hd :: tl -> tailrev ~r:(hd :: r) tl def rev(l): if l == []: return [] else: return rev(l[1:]) + [l[0]] def tailrev(l,r=[]): if l == []: return r else: return tailrev(l[1:],[l[0]]+r) Result of recursive call is also result of entire function In OCaml, tail recursion uses constant stack space

Functions as parameters # let l = [3;5;7];; val l : int list = [3; 5; 7] # List.map (fun x -> x*2) l;; -: int list = [6; 10; 14] # List.fold_left (fun x y -> x + y) 0 l;; -: int = 15 # List.filter (fun x -> x > 4) l;; - : int list = [5; 7] # List.iter (Printf.printf "%i\n") l;; : unit = () >>> l = [3,5,7] >>> map(lambda x: x*2,l) [6, 10, 14] >>> [x*2 for x in l] [6, 10, 14] >>> reduce(lambda x,y:x+y,l,0) 15 >>> filter(lambda x: x>4,l) [5, 7] >>> for x in l:... print x

Quicksort PYTHON def sort(a): if a == []: return [] else: pivot = a[0] left = [x for x in a if x < pivot] right = [x for x in a[1:] if x >= pivot] return sort(left) + [pivot] + sort(right) OCaml let rec quicksort l = match l with [] -> [] | pivot :: t -> let left = List.filter (fun x -> x < pivot) t in let right = List.filter (fun x -> x >= pivot) t in (quicksort (quicksort right)

Palindrome PYTHON def palindrome(s): if len(s) <= 1: return True return s[0] == s[-1] and palindrome(s[1:-1]) OCaml let rec palindrome s = s = (tailrev s)