ML Introduction.1 Standard ML Introduction. ML Introduction.2 Includes: Most of the examples Most of the questions Most of the answers... Recommended.

Slides:



Advertisements
Similar presentations
More ML Compiling Techniques David Walker. Today More data structures lists More functions More modules.
Advertisements

A First Look at ML.
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.
Cs776 (Prasad)L4Poly1 Polymorphic Type System. cs776 (Prasad)L4Poly2 Goals Allow expression of “for all types T” fun I x = x I : ’a -> ’a Allow expression.
Programming Languages and Paradigms The C Programming Language.
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 =
A First Look at ML Chapter FiveModern Programming Languages, 2nd ed.1.
Lecture 2 Introduction to C Programming
Introduction to C Programming
Compiler Construction
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Functional Design and Programming Lecture 1: Functional modeling, design and programming.
C Programming Language 4 Developed in 1972 by Dennis Ritchie at AT&T Bell Laboratories 4 Used to rewrite the UNIX operating system 4 Widely used on UNIX.
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.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Data types and variables
CSE S. Tanimoto Syntax and Types 1 Representation, Syntax, Paradigms, Types Representation Formal Syntax Paradigms Data Types Type Inference.
1 Functional Programming and ML. 2 What’s wrong with Imperative Languages? State State Introduces context sensitivity Introduces context sensitivity Harder.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
Chapter 2 Data Types, Declarations, and Displays
Introduction to C Programming
Admin Office hours 2:45-3:15 today due to department meeting if you change addresses during the semester, please unsubscribe the old one from the.
Introduction To C++ Programming 1.0 Basic C++ Program Structure 2.0 Program Control 3.0 Array And Structures 4.0 Function 5.0 Pointer 6.0 Secure Programming.
Basic Elements of C++ Chapter 2.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Objectives You should be able to describe: Data Types
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
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.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CSE-321 Programming Languages Introduction to Functional Programming (Part II) POSTECH March 13, 2006 박성우.
Programming Language Concepts (CIS 635) Elsa L Gunter 4303 GITC NJIT,
Introduction to Functional Programming and ML CS 331 Principles of Programming Languages.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Chapter 9: Functional Programming in a Typed Language.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
What is a Type? A type is a name for a collection of related values. For example, in Haskell the basic type Bool contains the two logical values: True.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
Copyright Curt Hill Variables What are they? Why do we need them?
Copyright © – Curt Hill Types What they do.
Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
A FIRST LOOK AT ML Chapter Five Modern Programming Languages 1.
Haskell. 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.
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.
CSE-321 Programming Languages Introduction to Functional Programming POSTECH March 8, 2006 박성우.
1 PROGRAMMING IN HASKELL Lecture 2 Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
Definition of the Programming Language CPRL
Principles of programming languages 12: Functional programming
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
Representation, Syntax, Paradigms, Types
Haskell.
CSE 3302 Programming Languages
2.1 Parts of a C++ Program.
Introduction to C++ Programming
Representation, Syntax, Paradigms, Types
CSE 341 Section 5 Winter 2018.
Representation, Syntax, Paradigms, Types
Haskell Types, Classes, and Functions, Currying, and Polymorphism
CSE-321 Programming Languages Introduction to Functional Programming
Chapter 2: Introduction to C++.
Representation, Syntax, Paradigms, Types
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Lexical Elements & Operators
Presentation transcript:

ML Introduction.1 Standard ML Introduction

ML Introduction.2 Includes: Most of the examples Most of the questions Most of the answers... Recommended Text Book L. C. Paulson, ML for the WORKING programmer Cambridge University Press, 1992.

ML Introduction.3 Loading and Saving  Interpreter  First prompt (-) and secondary prompt (=)  Need ; after each expression/definition  Loading ML source text from a file  Create a file named “myfile.sml”  Either start ML and use the function use: string -> unit - use “c:\\myfile.sml”; Don’t forget the double ‘\’ in the path!  Or redirect the input and output C:\ sml output

ML Introduction.4 A simple tutorial  ML is usually used as interpreter a compiler is also available  Expressions followed by a semicolon yield a response - 2+2; val it = 4 : int  Doing simple arithmetic ; val it = 0.9 : real - Math.sqrt(2.0); val it = : real

ML Introduction.5 Declaring Constants  Naming constants - val seconds = 60; val seconds = 60 : int  minutes per hour - val minutes = 60; val minutes = 60 : int  hours per day - val hours = 24; val hours = 24 : int  Using names in expressions - seconds * minutes * hours; val it = : int

ML Introduction.6 The identifier ‘it’  By referring to it, one can use the last value - it div 24; val it = 3600 : int  Any previous value of it is lost unless saved - val secsinhour = it; val secsinhour = 3600 : int;  Underscores can be used in names for readability - val secs_in_hour = seconds * minutes; val secs_in_hour = 3600 : int

ML Introduction.7 Legal Names - Alphabetic Names  Alphabetic name Begins with a letter Then followed by letters, digits, underscore, or single quotes Examples: x UB40 Hamlet_Prince_of_Denmark h’’3_H or_any_other_name_that_is_as_long_as_you_like Case of letters matters ML was designed by Mathematicians who like primes x, x’, x’’, x’’’

ML Introduction.8 Legal Names - Symbolic Names  Permitted over the characters: ! % & $ # + - * / : \ ~ ‘ ^ |  May be as long as you like: ----> $^$^$^$ :_|==>->#  Should not be one of the ML reserved special syntax: : _ | = => -> #  Allowed whenever an alphabetic name is: - val = 1415; val = 1415 : int  Very confusing! So try to avoid it.

ML Introduction.9 ML’s keywords abstype and andalso as case datatype do else end eqtype exception fn fun functor handle if in include infix infixr let local nonfix of op open orelse raise rec sharing sig signature struct structure then type val while with withtype  Avoid ML’s keywords when choosing names  Especially watch out from the short ones: as fn if in of op

ML Introduction.10 ML Primitive Types int, real, string, char, bool, unit

ML Introduction.11 Integer Types  Constants  sequence of digits  ~ for a unary minus sign ~23 ~  Infix operations: + - * div mod  Conventional precedence (((m * n) * l) - (m div j)) + j parenthesis can be dropped without change of meaning.

ML Introduction.12 Real types  Constants  decimal point  E notation 7E~5 ~1.2E12 ~123.4E~2 is the same as ~1.234  ~ for unary minus  Infix operators + - * /  Functions floor(r) converts real to int, real(i) converts int to real sqrt, sin, cos, tan, exp, ln all of type real -> real All need the Math prefix: Math.sqrt, Math.sin Infix operators have lower precedence.

ML Introduction.13  Constants are written in double quotes - "ML is the best"; val it = “ML is the best” : string  Special characters \n \t \" \\  Concatenation - "Standard" ^ " ML"; val it = "Standard ML" : string  size returns the number of characters - size (it); val it = 11 : int  Infix operators <, ^ Strings size("") is 0

ML Introduction.14 Characters  Chars are distinguished from strings of length 1 by the # sign - ”0”; val it = "0" : string - #”0”; val it = #"0" : char  Converting between strings and characters using str and sub - str(#”0”); val it = "0" : string - String.sub(”hello”,0); val it = #"h" : char  Converting chars to and from ASCII using ord and chr - ord #”0”; val it = 48 : int - chr it; val it = #”0” : char

ML Introduction.15 Boolean  The two values are - true; val it = true : bool - false; val it = false : bool

ML Introduction.16  (x1, x2,...,xn) The n-tuple whose components are x1,x2,...,xn. The components can be of any type, including tuples.  Examples – val a = (1.5, 6.8); val a = (1.5, 6.8) : real * real – (1, 1.5); val it = (1, 1.5) : int * real – ("str",1,true,(#"0",0.1)); val it = ("str",1,true,(#"0",0.1)) : string * int * bool * (char * real) Tuples Cartesian Product Type

ML Introduction.17 Records  Records have components (fields) identified by name - val me = { name="Ofir", age=30 }; val me = {age=30,name="Ofir"} : {age:int, name:string}  Type lists each field as label : type  Enclosed in braces {... }  Selecting a field - #name(me); val it = "Ofir" : string  Tuples can be seen as records with numbers as implicit field labels (x1,x2,...,xn) is {1=x1, 2=x2,..., n=xn} - #2 ("one", "two", "three"); val it = "two" : string

ML Introduction.18 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  Elements may appear more than once [3,4] [4,3] [3,4,3] [3,3,4]  Elements may have any type. But all elements of a list must have the same type. [(1,"One"),(2,"Two")] : (int*string) list [[3.1],[],[5.7, ~0.6]]: (real list) list

ML Introduction.19 Mapping - Functions  - fun sq(x:int) = x*x; val sq = fn : int -> int keyword fun starts the function declaration sq is the function name x :int is the formal parameter with type constraint x*x is the body and it is an expression the type of a function is printed as fn The result of the function is the result of evaluating the expression of the function body with the actual parameter int -> int is the standard mathematical notation for a function type that takes a integer number and returns a integer number

ML Introduction.20 Applying a Function  Simple function call - sq (3); val it = 9 : int  When a function is called the parameter is evaluated and then passed to the function (seems obvious but it is not always the case in functional languages…) - sq (sq(3)); val it = 81 : int  The parentheses around the argument are optional - sq 3; val it = 9 : int  Parentheses are also optional in function definitions - fun sq x:int = x*x; val sq = fn: int -> int

ML Introduction.21 Arguments and Results  Every function has one argument and one result.  Any type can be passed/returned !!!  Tuples are used to pass/return several arguments - val a = (1.5, 6.8); val a = (1.5, 6.8) : real * real - fun lengthvec (x:real,y:real) = sqrt(x*x + y*y); val lengthvec = fn : real * real -> real - lengthvec a; val it = : real - fun negvec (x:real,y:real) = (~x, ~y); val negvec = fn : real * real -> real * real - negvec (1.0, 1.0); val it = (~1.0, ~1.0) : real * real

ML Introduction.22 Functions as Values  Anonymous functions with fn notation - fn x:int => x*x; val it = fn : int -> int - it(3); val it = 9 : int  The following declarations are identical fun sq x:int = x*x; val sq = fn x:int => x*x

ML Introduction.23 Function as Return Value  Functions can also be returned from other functions - fun inttwice(f:(int->int)) = fn x => f(f(x)); val inttwice = fn : (int -> int) -> int -> int  The arrow associates to the right so the last line is equivalent to val inttwice = fn : (int -> int) -> (int -> int)  Example - inttwice(fn x => x*x); val it = fn : int -> int - it(3); val it = 81 : int - it(2); Error: operator is not a function

ML Introduction.24 Type Inference  ML deduces the types in expressions  Type checking the function: fun facti (n,p) = if n=0 then p else facti(n-1,n*p); val facti = fn : int * int -> int constants 0 and 1 have type int therefore n=0 and n-1 involve integers so n has type int n*p must be integer multiplication, so p has type int facti returns type int, and its argument type is int*int

ML Introduction.25  Certain functions are overloaded, e.g., abs,+,-,~,*,<.  Type of an overloaded function is determined from context, or is set to int by default.  Types can be stated explicitly.  Examples: - fun min(x,y) = if x < y then x else y; val min = fn : int * int -> int - fun min(x:real,y) = if x < y then x else y; val min = fn : real * real -> real - fun min(x:string,y) = if x < y then x else y; val min = fn : string * string -> string - fun min(x,y):real = if x < y then x else y; val min = fn : real * real -> real - fun min(x,y) = if x < y then x:real else y; val min = fn : real * real -> real Type Constraints

ML Introduction.26 Polymorphic type checking  Weakly typed languages (e.g.. Lisp) give freedom  Strongly typed languages (e.g. Pascal) give security by restricting the freedom to make mistakes  Polymorphic type checking in ML security of strong type checking great flexibility (like weak type checking) most type information is deduced automatically an object is polymorphic if it can be regarded as having any kind of type

ML Introduction.27 Polymorphic function definitions  If type inference leaves some types completely unconstrained then the definition is polymorphic  A polymorphic type contains a type variable, e.g. 'a  Example: - fun pairself x = (x,x); val pairself = fn : 'a -> 'a * 'a - pairself 4.0; val it = (4.0,4.0) : real * real - pairself “NN”; val it = (“NN”,”NN”) : string * string - pairself (1.0,3); val it =((1.0,3),(1.0,3)):(real*int)*(real*int) - fun pair (x,y) = (y,x); val pair = fn: (‘a * ’b) -> (‘b * ’a)

ML Introduction.28 Functions as Values The Polymorphic Case Functions as Values The Polymorphic Case - fun twice f = fn x => f(f(x)); val twice = fn : ('a -> 'a) -> 'a -> 'a - fun ident x = x; val ident = fn : 'a -> 'a - twice (fn x => x*x); val it = fn : int -> int - it(2); val it = 16 : int

ML Introduction.29 Functions as Values The Polymorphic Case (cont.)  Sometimes ML gives us hard time when we give polymorphic value to polymorphic function. For example: - twice ident; stdIn:… Warning: type vars not generalized because of value restriction are instantiated to dummy types (X1,X2,...) val it = fn : ?.X1 -> ?.X1  The reason for this is outside the scope of this course. You usually may ignore it. Or, if needed, workaround the problem: - fn x => (twice ident)(x); val it = fn : 'a -> 'a

ML Introduction.30 Functional vs. Imperative  Imperative - using commands to change the state.  Functional - stateless. Using expressions recursively to calculate the result.  Example: Euclid’s Algorithm for the Greatest Common Divisor (GCD) of two natural numbers: How would a GCD program would look like in functional vs. imperative language?

ML Introduction.31 GCD - Pascal vs. ML function gcd(m,n: integer): integer; var prevm: integer; begin while m<>0 do begin prevm := m; m := n mod m; n := prevm end; gcd := n end; fun gcd(m,n) = if m=0 then n else gcd(n mod m, m);  An imperative Pascal Program:  A functional program in Standard ML: