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.

Slides:



Advertisements
Similar presentations
Modern Programming Languages, 2nd ed.
Advertisements

Lisp. Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks.
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
Introduction to OCaml Slides prepared by Matt Gruskin Some material borrowed from the CIS 500 lecture notes.
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.
CSE 3341/655; Part 4 55 A functional program: Collection of functions A function just computes and returns a value No side-effects In fact: No program.
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 =
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.
CS 355 – PROGRAMMING LANGUAGES Dr. X. Apply-to-all A functional form that takes a single function as a parameter and yields a list of values obtained.
LISP Programming. LISP – simple and powerful mid-1950’s by John McCarthy at M.I.T. “ LIS t P rocessing language” Artificial Intelligence programs LISP.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
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 =
Chapter 15 Other Functional Languages. Copyright © 2007 Addison-Wesley. All rights reserved. Functional Languages Scheme and LISP have a simple syntax.
PHYS 2020 Making Choices; Arrays. Arrays  An array is very much like a matrix.  In the C language, an array is a collection of variables, all of the.
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:
Even More C Programming Pointers. Names and Addresses every variable has a location in memory. This memory location is uniquely determined by a memory.
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
COP 3275 COMPUTER PROGRAMMING USING C Instructor: Diego Rivera-Gutierrez
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
Haskell. 2 GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
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.
Introduction to Functional Programming and ML CS 331 Principles of Programming Languages.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #005 (April somthin, 2015)
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
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.
CSC 107 – Programming For Science. The Week’s Goal.
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.
CSE 341 : Programming Languages Lecture 2 Functions, Pairs, Lists Zach Tatlock Spring 2014.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
This will all add up in the end. Assignment operator =Simple Assignment operator Arithmetic Operators +Additive operator – Subtraction operator * Multiplication.
Arithmetic Expressions Addition (+) Subtraction (-) Multiplication (*) Division (/) –Integer –Real Number Mod Operator (%) Same as regular Depends on the.
Introduction to Objective Caml. General comments ML is a purely functional language--there are (almost) no side effects There are two basic dialects of.
Introduction to LISP Atoms, Lists Math. LISP n LISt Processing n Function model –Program = function definition –Give arguments –Returns values n Mathematical.
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
ISBN Chapter 15 Functional Programming Languages.
Functional Programming. Some Functional Languages Lisp Scheme - a dialect of Lisp Haskell Miranda.
Ada, Scheme, R Emory Wingard. Ada History Department of Defense in search of high level language around Requirements drafted for the language.
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
A Sample Program #include using namespace std; int main(void) { cout
1 Outline Review Introduction to LISP Symbols and Numbers Lists Writing LISP Functions LISPWorks.
Functional Programming
Functional Programming
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
Multiple variables can be created in one declaration
Variables, Expressions, and IO
Intro to C Tutorial 4: Arithmetic and Logical expressions
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
6 Chapter Functions.
FP Foundations, Scheme In Text: Chapter 14.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
Default Parameters February 24, 2016
Lesson #6 Modular Programming and Functions.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Common Lisp II.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
Presentation transcript:

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 –the type of add is int * int -> int –the -> denotes a function –Therefore, a function is a kind of value! –The actual value is abbreviated to

Another function definition # let double x = x + x;; val double : int -> int = Why don't we need parentheses around the parameter x ? Every function in OCaml takes one parameter and returns one result. –The parameter may be a tuple –The result may be a tuple

add again # let add (x, y) = x + y;; val add : int * int -> int = # add (7, 3);; - : int = 10 # add (3.0, 5.0);; Characters 5-13: This expression has type float * float but is here used with type int * int OCaml is strongly typed, but it can deduce types

Statements in OCaml There are no statements in OCaml OCaml is (almost) a purely functional language; it has no side effects* –but OCaml does have expressions Every expression has a value * Except for output "statements"--we won't be doing output

The if...then...else expression if boolean-expression then expression 1 else expression 2 The else part is required (why?) –because the if expression must have a value expression 1 and expression 2 must have the same type –because OCaml is strongly typed –it needs to know the type of the expression

Using if...then...else # let max (x, y) = if x > y then x else y;; val max : 'a * 'a -> 'a = # max (7, 5);; - : int = 7 # max (7.0, 5.0);; - : float = max, as defined here, is a polymorphic function

Integer division, with remainder # let divide (x, y) = x / y, x mod y;; val divide : int * int -> int * int = # divide (20, 3);; - : int * int = 6, 2 We aren't returning two results, just one--but it's a tuple Similarly, we're only providing one parameter

Adding vectors # let addVec ((x1, y1), (x2, y2)) = (x1 + x2, y1 + y2);; val addVec : (int * int) * (int * int) -> int * int = # addVec ((3, 5), (10, 20));; - : int * int = 13, 25 Notice that parentheses are sometimes necessary

LISP-like operations Recall that OCaml has the following operations: –hd returns the head of a list –tl returns the tail of a list –:: adds an element to a list These are essentially the same as CAR, CDR, and CONS in LISP Can we define CAR, CDR, and CONS in OCaml?

Redefining LISP # let car x = List.hd x;; val car : 'a list -> 'a = # let cdr x = List.tl x;; val cdr : 'a list -> 'a list = # let cons (x, y) = x :: y;; val cons : 'a * 'a list -> 'a list = # car (cdr [1; 2; 3; 4]);; - : int = 2

Testing our LISP functions cons ([1; 2], [3; 4]);; # Characters 6-20: This expression has type int list * int list but is here used with type int list * int list list Elements of list must be same type! There is no solution (with the OCaml we know so far)

Trapped in time # let age = 20;; val age : int = 20 # let older () = age + 1;; val older : unit -> int = # older ();; - : int = 21 # let age = 35;; val age : int = 35 # older ();; - : int = 21

OCaml adds to state, doesn't change it OCaml has no "assignment" let age = 21; associates age with 21 This age is then used in function older let age = 35; associates a new age with 35 The old age goes out of scope, but it doesn't go away (it's lifetime is not over) older still uses the original variable

Functions are values, too # let f x = 2 * x;; val f : int -> int = # let g x = f (f x);; val g : int -> int = # g 5;; - : int = 20 # let f x = 3 * x;; val f : int -> int = # g 5;; - : int = 20

Debugging functions You saw that redefining a function does not affect prior uses of that function Therefore, you can't change a function by changing something it calls Everything should work OK if you compile all your functions from a file every time Sometimes you just have to restart OCaml

It's all in the binding times OCaml's approach seems strange, but you have seen it before x = 5; y = 2 * x; x = x + 1; print "y = ", y; Would you expect y = 12 to be printed? Remember, functions are values too!

The End