Introduction to Functional Programming and ML CS 331 Principles of Programming Languages.

Slides:



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

A First Look at ML.
C-LISP. LISP 2 Lisp was invented by John McCarthy in 1958 while he was at the Massachusetts Institute of Technology (MIT).John McCarthyMassachusetts Institute.
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.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
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 =
Chapter 3 Functional Programming. Outline Introduction to functional programming Scheme: an untyped functional programming language.
Chapter ElevenModern Programming Languages1 A Fourth Look At ML.
A Fourth Look At ML Chapter ElevenModern Programming Languages, 2nd ed.1.
A First Look at ML Chapter FiveModern Programming Languages, 2nd ed.1.
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.
Introduction to ML – Part 1 Frances Spalding. Assignment 1 chive/fall05/cos441/assignments/a1.ht m
5/11/2015IT 3271 Types in ML (Ch 11) datatype bool = true | false; datatype 'element list = nil | :: of 'element * 'element list n Predefined, but not.
ML Exceptions.1 Standard ML Exceptions. ML Exceptions.2 Exceptions – The Need  An extensive part of the code is error handling  A function can return.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
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.
Javascript II Expressions and Data Types. 2 JavaScript Review programs executed by the web browser programs embedded in a web page using the script element.
1 Functional Programming and ML. 2 What’s wrong with Imperative Languages? State State Introduces context sensitivity Introduces context sensitivity Harder.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
ML Introduction.1 Standard ML Introduction. ML Introduction.2 Includes: Most of the examples Most of the questions Most of the answers... Recommended.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Imperative Programming
CS235 Languages and Automata Department of Computer Science Wellesley College Introduction to Standard ML Wednesday, September 23, 2009 Reading: Beginning.
ISBN Chapter 15 Functional Programming Languages.
Programming Language Concepts (CIS 635) Elsa L Gunter 4303 GITC NJIT,
Linux Operations and Administration
Slides to accompany Ullman’s Functional Programming with ML CS 631 Principles of Programming Languages.
Introduction to ML CS 331 Principles of Programming Languages revised Spring 2003.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Chapter 9: Functional Programming in a Typed Language.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use 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.
Chapter SevenModern Programming Languages1 A Second Look At ML.
A FIRST LOOK AT ML Chapter Five Modern Programming Languages 1.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
CSE 341 Lecture 8 curried functions Ullman 5.5 slides created by Marty Stepp
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Cs776(Prasad)L6sml971 SML-97 Specifics SML/NJ 110.
1.SML Docs Standard Basis 2.First-Class Functions Anonymous Style Points Higher-Order 3.Examples Agenda.
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Functional Programming
Principles of programming languages 12: Functional programming
Chapter 6 JavaScript: Introduction to Scripting
CSE 220 – C Programming C Fundamentals.
ML: a quasi-functional language with strong typing
Completing the Problem-Solving Process
ML Again ( Chapter 7) Patterns Local variable definitions
Introduction to Scripting
Programmazione I a.a. 2017/2018.
Introduction to Functional Programming in Racket
Introduction to C++ Programming
An aggregation mechanism
T. Jumana Abu Shmais – AOU - Riyadh
Introduction to C Topics Compilation Using the gcc Compiler
Building Java Programs
Introduction to Functional Programming in Racket
CSE-321 Programming Languages Introduction to Functional Programming
Introduction to C Topics Compilation Using the gcc Compiler
CSE 341 Lecture 2 lists and tuples; more functions; mutable state
Presentation transcript:

Introduction to Functional Programming and ML CS 331 Principles of Programming Languages

How to do screen captures

Features of ML A pure functional language – serious programs can be written without using variables Widely accepted –reasonable performance (claimed) –syntax not as arcane as LISP

In these slides, We use Standard ML of New Jersey Runs on PCs, and lots of other platforms See the ML API documentation at labs.com/cm/cs/what/smlnj/doc/basis/pages/sml-std- basis.html For information about ML on the web, see – –

Running SML on Windows On Windows, it’s invoked from the Programs menu under the Start button Also possible to run from MS-DOS prompt, e.g. C: sml\bin\sml-cm <foo.sml –note that a set of function definitions can be read in this way automatically Use control z to exit interpreter

Running SML on UNIX On gl, execute this command: ~nicholas/../pub/331/smlnj/bin/sml-cm Use control d to exit interpreter

Hello, world in SML Standard ML of New Jersey, - print("Hello world\n"); Hello world val it = () : unit -

Arithmetic in ML Copy and paste the following text into a Standard ML window 2+2; (* note semicolon at end*) 3*4; 4/3; (* an error! *) 6 div 2; (* integer division *) 7 div 3;

It should look like this

Declaring Constants Constants are not exactly the same as variables –once set, they can’t be modified –they can be redefined, but existings uses of that constant (e.g. in functions) aren’t affected by such redefinition val freezingFahr = 32;

Declaring Functions A function takes an input value and returns an output value ML will figure out the types fun fahrToCelsius f = (f -freezingFahr) * 5 div 9; fun celsiusToFahr c = c * 9 div 5 + freezingFahr;

Notes ML is picky about not mixing types, such as int and real, in expressions The value of “it” is always the last value computed Function arguments don’t always need parentheses, but it doesn’t hurt to use them

Types of arguments and results ML figures out the input and/or output types for simple expressions, constant declarations, and function declarations If the default isn’t what you want, you can specify the input and output types, e.g. fun divBy2 x:int = x div 2 : int; fun divideBy2 (y : real) = y / 2.0; divBy2 (5); divideBy2 (5.0);

Two similar divide functions - fun divBy2 x:int = x div 2 : int; val divBy2 = fn : int -> int - fun divideBy2 (y : real) = y / 2.0; val divideBy2 = fn : real -> real - divBy2 (5); val it = 2 : int - divideBy2 (5.0); val it = 2.5 : real -

Ints and Reals Int.abs ~3; Int.sign ~3; Int.max (4, 7); Int.min (~2, 2); real(freezingFahr); Math.sqrt real(2); Math.sqrt(real(2)); Math.sqrt(real 3); Note ~ is unary minus min and max take just two input arguments, but that can be fixed! Real converts ints to real Parens can sometimes be omitted

- Int.abs ~3; val it = 3 : int - Int.sign ~3; val it = ~1 : int - Int.max (4, 7); val it = 7 : int - Int.min (~2, 2); val it = ~2 : int - real(freezingFahr); val it = 32.0 : real - Math.sqrt real(2); stdIn: Error: operator and operand don't agree [tycon mismatch] operator domain: real operand: int -> real in expression: Math.sqrt real - Math.sqrt(real(2)); val it = : real - Math.sqrt(real 3); val it = : real -

Strings Delimited by double quotes the caret mark ^ is used for string concatenation, e.g. “house”^”cat” \n is used for newline, as in C and C++

Lists in ML Objects in a list must be of the same type –[1,2,3]; –[“dog”, “cat”, “moose”]; The empty list is written [] or nil

Making Lists operator is used to concatenate two lists of the same type The functions hd and tl give the first element of the list, and the rest of the list, respectively

List Operations - val list1 = [1,2,3]; val list1 = [1,2,3] : int list - val list2 = [3,4,5]; val list2 = [3,4,5] : int list - val it = [1,2,3,3,4,5] : int list - hd list1; val it = 1 : int - tl list2; val it = [4,5] : int list

Strings and Lists The explode function converts a string into a list of characters The implode function converts a list of characters into a string Examples: - explode("foo"); val it = [#"f",#"o",#"o"] : char list - implode [#"c",#"a",#"t"]; val it = "cat" : string -

Heads and Tails The cons operator :: takes an element and prepends it to a list of that same type. For example, the expression 1::[2,3] results in the list [1,2,3] What’s the value of [1,2]::[ [3,4], [5,6]] ?

Functions and Patterns Recall that min and max take just two arguments However, using the fact that, for example, –min(a, b, c) = min(a, min(b, c))

Generalizing Min An example of ML pattern matching –the cons notation x::xs is both a binary constructor and a pattern –cases aren’t supposed to overlap fun multiMin (x: int) = x | multiMin (x:int, y:int) = Int.min(x y) | multiMin (x::xs) = Int.min(x, multiMin(xs));

Iteration vs. Recursion (* note that F is a functional parameter *) fun loopIt(i:int,n:int,F) = if i = n then F(i) else let val dummy = F(i) val dummy2 = loopIt(i+1,n,F) in dummy2 (* any expression could be used *) end;