<<

INF 3040 - 2020 Universityof Oslo – Stolz ML 1 ML – IN3040 IN3040 [email protected] Volker John . slidesMitchell’s (Stanford U.) Initially by Gerardo Schneider. Gerardo by Initially Based on Departmentof Informatics The Algol family and SML and family Algol The 18.09.20 IN3040 - 2020 ML 1 ML – IN3040 IN3040 II / The The Algol Family and SML Moreon Types, Type and MoreTypes& on ML (chap.and 6) 5

Continuations(chap. 8) Prolog I 16.10: Polymorphism(chap. 6) Controlsequential in languages, Exceptions and 25.09: 18.09: 5) chap. (Mitchell’s

18.09.20 SML lectures

! ! ! ! ! IN3040 - 2020 constructs constructs - ”power - ) Haskell use equivalents of SML equivalents - Don’t ML 1 ML – SML in exercises and the exam! (*) theexam! and inexercises SML of apply! like programminglike languages IN3040 IN3040 - instead video snippets showing the differences. the showing snippets video conditions 68 short Haskell notation, language extensions, infinite datastructure) extensions, notation,language - and use (Mitchell, Chapter 5 Chapter (Mitchell, prepare SML may Terms ., no “do”

will ie (*) we’ll features”, only theHaskelladmit ( You I Pascal/ C

• • • • •

Noteworthyyear: this Basic Basic Brief overview Brief Algol of Algol 60/Algol

!

! !

18.09.20 Outline IN3040 - 2020 Modula 67, BCPL, 67, ML 1 ML – Pascal Algol 68 Algol 60 IN3040 IN3040 Simula 3 (DEC), Delphi, … - ML 2, 2, Oberon, Modula - late 50s (McCarthy, MIT) (McCarthy, Modula Algol 58, Algol W, Euclid, Ada, Euclid,Ada, Algol W, Algol58,

Lisp Lisp

18.09.20

A (partial) Language Sequence (partial)Language A Many other languages inthe“family”: other languages Many IN3040 - 2020 ] y ML 1 ML – IN3040 IN3040 + [3]* A[x (J. Backus, J. McCarthy, J. Backus, (J. A. Perlis,…) 1963 - General array references: calls procedure in Parameters Statement oriented variables) (local { …} ) C (like blocks …end begin if … then … else syntax describing for standard the Became

– – – – – –

Primitive static ALGOL became a standard language to describe . Recursive functions and stack storage allocation Fewer than ad restrictions hoc BNF (Backus Normal Form) Normal (Backus BNF Simple imperative language + functions Successful syntax, used by many successors

• • • • • • •

Designed: 1958 Designed: Features: language. Generalpurpose

! !

18.09.20 Algol 60 Algol IN3040 - 2020 here no array bounds array no “;” no ML 1 ML – IN3040 IN3040 set procedure return value by assignment by value return procedure set sum := sum + A[i]; + sum := sum

averagesum/n := real sum; sum := 0; := realsum sum; don stepuntil 1 1 = for i

end; realarray n; A; begin

realprocedure average(A,n);

18.09.20 Algol 60 Sample Algol IN3040 - 2020 parameter procedure ML 1 ML – IN3040 IN3040 had various had anomalies(side effects) expensive for arrays expensivefor value name - - by by out of a requires memory management a block memory of requires out - - no array no bounds no argument or return argument for no types

– – goto Pass Pass “procedure” can be a parameter type can a parameter be “procedure” Type “array”Type parameter as a procedure

• • • • •

Someawkward control issues Parameterpassing methods Shortcomingtypeof its discipline

!

! !

18.09.20 Some trouble spots in Algol 60 Algol spots in trouble Some IN3040 - 2020 (copy rule) k := k+1; k+1; := k A[k] := A[k] +1 begin begin end; ML 1 ML Is this what you expected? thiswhat you Is – IN3040 IN3040 name - by ); - j ; j ]); , i A[k , :=j+1 :=i+1; k j i end; integer integer begin Unpredictable with Unpredictable side effects!

inc2( procedure inc2(i, procedure •

Example Substitutetext ofactual parameter

! !

18.09.20 Algol 60 Pass Algol IN3040 - 2020 ) reference - by - pass ML 1 ML – IN3040 IN3040 and garbage collection garbage and reference using pointers using reference - by - alloc name (introduced (introduced name - by - value and pass valueand - by - types werecalled “modes” values” “multiple called were arrays – – Elaborate type system (e.g. array of pointersto Elaborate procedures) (e.g. type system type Complicated conversions New terminology New Localstack storageon explicit storage, Heap Eliminatedpass Pass Systematic,regular type system

• • • • • • • •

Considered difficult to understand to difficult Considered Storage management Storage Intended to improve Algol 60 Algol improve to Intended passing Parameter

! !

! !

18.09.20 Algol 68 Algol IN3040 - 2020 (e.g. [1…10]) (e.g. (based on C.A.. Hoare’s ideas) C.A.R. on (based subranges (over20 years! 90s) the Till ML 1 ML – IN3040 IN3040 structuring concepts structuring passcompiler - - records, variants (union type), variants type), records, (union parameters cannot procedure parameters have Procedure – – Good data Good 60/68 restrictive Algol More than

• •

Simple one Simple Popularteaching language Evolved from Algol W Algol from Evolved Revised type systemof Algol Designedby N. Wirth(70s)

! ! ! ! !

18.09.20 Pascal Pascal IN3040 - 2020 ML 1 ML – IN3040 IN3040

Not allowed Not Allowed

procedure NotA(procedure Proc3(procedure P(i:integer))); NotA(procedure procedure

procedure Proc2(procedure P(i:integer); procedure integer); i,j: procedure Proc1(i,j: procedure integer);

! !

18.09.20 Procedure parameters in Pascal in parameters Procedure IN3040 - 2020 illegal strength”projects - ML 1 ML – procedure? IN3040 IN3040 sort Only for arrays of some fixed length fixed of some arrays Onlyfor • Types cannot contain variables Types Howto write generic a procedure p(n: integer, aarray : [1..n] integer) p(n: integer, of procedure procedure p(a array: procedure [1..10] integer) of

– – How could this have happened? Emphasis on teaching on Emphasis happened? Howthis could have Practical drawbacks: Practical

• Arraybounds part oftype

Not successful for “industrial for Notsuccessful

! 18.09.20

! Limitations of Pascal Limitations IN3040 - 2020 Modulesystem ML 1 ML – IN3040 IN3040 :implementation :interface Definition Implementationmodule module

– – Modules allow certain declarations to be grouped together allow Modules grouped certain be declarations to

informationhiding ModulesModula in provides minimal DescendentofPascal Maininnovation over Pascal: Designedby N. Wirth(late 70s)

! ! ! !

18.09.20 Modula IN3040 - 2020 2011 *((E1)+(E2)) ML 1 ML – dereference IN3040 IN3040 common in otherin languages common pointer not language; C adds some checking some adds C language; untyped Many like flexibility C programmers Many (?!) a as Howeverwellseen as weak just be type can checking disadvantage. Memory model close tohardware model theunderlying Memory An array An treatedis pointer a toas first element equivalentis to E1[E2] Pointerarithmetic is B was an an was B • • • • • • •

Popular language Popular Relation betweenarrays Relation pointers and Designed for writing Unix by Dennis Ritchieby Dennis Unix writing for Designed which B, Evolvedwas from BCPL based on

18.09.20

! ! ! ! C Programming C IN3040 - 2020 (or a mostly mostly a (or (but not only...) only...) not (but likefeatures ML 1 ML - – IN3040 IN3040 order functions, Garbage collection, Garbage orderfunctions, - like, not OOlanguage like,not - C - oriented, Higher oriented, - oriented imperative language -

Abstract data types, Module system, Exceptions system, AbstractModule datatypes, Expression function

• General purpose non purpose General Combination of Lisp and Algol Intended for interactive for use ... Intended Typed programming language. Clean and expressive and Clean type language. programming Typed A

Sound type systemtype (type Sound unpleasantlychecking), not but restrictive. system. functional language withfeatures) imperative language functional

!

! ! ! ! !

18.09.20 ML IN3040 - 2020 ML 1 ML – IN3040 IN3040 andto prove properties of

useful to useful know

Certainaspects are easier to understand and program(e.g. recursion) More compact (simple?) code code (simple?) compact More Higherorder functions Verifiableprogramming: Easier to reason about a language, functional programs All programming All languages have a“part” functional - Learnto think and solve problems ways new in

18.09.20 ! ! ! ! ! ! Why study ML ? ML study Why IN3040 - 2020 order functions order - ML 1 ML – (Mitchell’schapter 6) IN3040 IN3040 (Mitchell’schapter 7) (orHaskell)? (Mitchell’schapter 8) Functionactivation higher records, Exceptions Tailrecursion and delay Forceand General issues instatic/dynamic Generaltyping issues Type inference Generic Programming and Polymorphism blockStatic structure and – – – – – – – – Control Memory management management Memory Typescheckingtype and

• • •

Learna different PL issues general Discuss PL

! !

18.09.20 Why study ML ML study Why IN3040 - 2020 . prog . func ML 1 ML (70s and 80s) (70s – IN3040 IN3040 2010 anguage of the LCF system LCF the of anguage Too much work much toToo construct full formal hand proof by L

- • Make sure proofs are proofs correct sure Make Notationproofs for and assertions that Writeproofs find programs Projectto automate Notationfor programs Formulatelogic to prove properties of typed calculus. lambda (polymorphic) typed Simply

eta

– – – – – – – M Milner'sgoals Based on Dana Scott’sDana Basedon ideas (1969)

• •

Logic for Computable Logic Functions (LCF project) Designedby Milner R.

18.09.20 Origin of ML

! ! IN3040 - 2020 Language(ML) - ML 1 ML – IN3040 IN3040 succeed and return proof succeed return and fail to distinguish successful from tosuccessful distinguish ) = search ) = forever : function that function tries : ato proof find type system

tactic(formula

Usea proofs unsuccessful and to correctness facilitate Expressthe Meta in tactics Proof tactic

! ! !

18.09.20 LCF proof searchLCF IN3040 - 2020 raise exception ML 1 ML – IN3040 IN3040 succeed and return proof succeed return and fail and proof ® ) = search ) = forever safeexception mechanism! - Typesystem “failure” mustallow

tactic : formula

tactic(formula

First type First What if the Whatformulanot is if correct and there no is proof? Tactic has Tactic atype functional

!

! !

18.09.20 Tactics in ML type system type TacticsML in IN3040 - 2020 B Î ) f(x = y ML 1 ML – IN3040 IN3040 some element element some by raisingexception an terminate A, Î x ) = run forever run ) = B means B

f(x ®

for every for

: A

f

18.09.20 Function types in ML in types Function IN3040 - 2020 stylestatic safe way safe - - parametric classes, binary parametricclasses, ) - ML 1 ML – IN3040 IN3040 INRIA):with OO ML extended history.en. - 1997 specialization)staticallyina type SML Caml /about/ inria.fr mycamltype (Objective : Concurrent ML (INRIA, France) Concurrent : : Concurrent ML (USA) Concurrent : Advanced OO programming idioms: type idioms: programming OO Advanced methods, (see http://. First language that combines full power of OOP withfull that power of OOP ML combines Firstlanguage type inference and typing

• •

and a module system a module and Caml OCAML CML Developed into different dialects different into Developed ML1983, Standard

18.09.20 ! ! ! !

! Later development of ML development Later IN3040 - 2020 StandardML brackets,we?) do - ML 1 ML – code IN3040 IN3040 sml ”; sml (SML/NJ, v110.81) 1.6. ”Getting started” 1.6. filename.sml . And we Schemewant don’t the And . sml Pucella www.smlnj.org use ” ~ $ ~

– obligs See Note:to fileina read with From the prompt:

- stolz Standard ML of New Jersey v110.81 [Mon Sep 4 12:02:23 2017] • • •

the the (Yes,also it withmeansdealwe haveall but don’t it’sto old, Haskell usedifferent like in would you the to that extensions of New Jerseyof http:// course practicalwe the In the willof part use

!

! !

18.09.20 SML IN3040 - 2020 Patterns Declarations Functions declarations Type Cells Reference Polymorphism Overloading Exceptions ! ! ! ! ! ! ! ! ML 1 ML – IN3040 IN3040 (char) (bool) (int) (string) (real) (unit)

Lists Lists Records Reals Tuples Strings Strings Characters Booleans Booleans Unit Unit • • • • • • • • •

Basic Types Basic

!

18.09.20 Core ML IN3040 - 2020 print - eval - read ML 1 ML – IN3040 IN3040 “it” is an id bound to thevalue of last exp bound “it”id an is 2; - infers type before compiling or executing or compiling before typeinfers Compiler Expressionschecked,typeare executed and compiled

val greeting = “Hello”; valgreeting if 5>3 then “Big” else “Small”;“Big” 5>3 if then (5+3)

- = "Hello">string :val greeting - >valstring : = “Big” it - int : 6 = it val > • •

Examples SML has SML an Interactive compiler:

! !

18.09.20 Basic Overview of ML BasicOverview IN3040 - 2020 Error Error à à (op <)(1,5) but but 1.0 = 1.0 = 1.0 2 + 1.0 1 < 5 < 1 ML 1 ML – . . IN3040 IN3040 , no coercion. coercion. no , int bool ints > ® - . decimal point used todisambiguate used point decimal int int and and int * types must match; “else” is mandatory is “else” match; must types * ” ^ “Oslo” ^ ” reals i int int reals Oslo” : string : Oslo” 2, … : : … 2, i - ” ^ “ ^ ” bool 1, - , * , div … : : … div , * , - Universitetet Universitetet =,<,<=,>,<= : Cannot combine 1.0, 2.2, 3.14159, … … 3.14159, 2.2, 1.0, operator ‘=‘ No for “ #”a” (op >) turns the infix operator infix into function: > a (op the turns >) “ 0, 1, 2, … 2, 1, 0, +, true, false : …else … if…then

• • • • • • • • • • • •

Reals Char Strings Integers Booleans

! ! !

! !

18.09.20 Overview by Type IN3040 - 2020 true à ML 1 ML – in C in IN3040 IN3040 void . > val it = “Jones”= stringit : val > Error à infixconsnotation similar to {name="Jones", name="Jones"}; = {age=34, age=34} (34,”Jones”) = (“Jones”,34) > val it = [1,2,3,4] : int list int : [1,2,3,4] = it val > nil; 1 :: nil ; 1::(2::(3::(4::nil))) 1 :: [2, 3, 4]; list int : [1,2,3,4] = it val > [3,4] @ [1,2] > val it = "ha det" : string"hadet" = : it val > Are tuples with labeled fields: {name=“Jones”, {name: age=34}: string, age: int}; #name({name=“Jones”,age=34}); matter: not does Order (1 , 2) : int * int ; int * : int 2) , (1 string; * int * :int det!”) “ha 5, (4, #3(4, 5, “ha det!”) unit – – – – – – – – – – – – () : () : •

Lists Records Unit Tuples

! ! ! !

18.09.20 Compound Types IN3040 - 2020 (more later) (more ML 1 ML – IN3040 IN3040 > val name = “Gerardo" : string val = = val > val mypi = 3.1415 : real val x::rest = myList; = x::rest val val myTuple = (“Carlos”, “Johan”); (“Carlos”, = myTuple val myTuple; = (x,y) val 4]; 3,2, [1, = myList val letval =2+3x*4end; x in int 20: = valit > - - - - Localdeclarations Examples: Examples: Generalform :

::= | | | | | | | | ::= val mypi = 3.1415; = mypi val “Gerardo”; = string : name val

• • • - - valkeyword, annotations type

Valuedeclarations Patternsplaceidentifiers can in used of be

! ! !

18.09.20 Value declarations and patterns and declarations Value IN3040 - 2020 x . (x * 2) l > int - ML 1 ML – > int - IN3040 IN3040 > val dbl = fn : int > | … 1 > n Anonymous function Anonymous Actual par. must match pattern (x,y) pattern match must par. Actual > val dbl = fn : int “anonymous function”, in lambda notation lambdanotation in function”, “anonymous > val it = 3 : int > int > int - - > = = x * 2 ; ; 2 * x => x fn = dbl val ; 2 * x = x dbl fun (5*6) ; ; (5*6) ; 2 * x => x fn clause definition clause - fn (x,y) => x+y; x+y; => (x,y) fn - - - - - > val it = 30 : int - > val it = fn : int | | | length (x::s) = 1 + length(s); + 1 = (x::s) length | fun fun 0 = (nil) length fun fun f () = = () f fun => fn But we have a special syntax for defining functions: Functions are as other values: values: other as are Functions length [“J”, ”o”, “n”] “n”] ”o”, [“J”, length

> val length = fn - • - • • • • Multiple Function declaration, generalFunction form Function declaration Function

18.09.20 Functions and Pattern and Functions

!

! ! IN3040 - 2020 ML 1 ML – IN3040 IN3040 elsee::(x::xs);

append ([3,4],[1,2]) append ; insert (3,[1,2,5])insert ;

| insert (e,insert x::xs) insert(e,xs):: x | =e>x then if - list int : [3,4,1,2] = it >val fun append(nil, ys) append(nil, fun = ys append(x::xs, ys) | append(xs,=::ys); x - list int : [1,2,3,5] = it val > fun insert (e,insert = nil) [e] fun

Appendlists Insertanan elementordered in list

! !

18.09.20 Some functionson lists IN3040 - 2020 Constructors! - < ML 1 ML – IN3040 IN3040

type declarations declarations type elements are: I(9) , R(8.3) , S(“hello”) ... S(“hello”) , R(8.3) , I(9) are: elements ... IntVal(“foo”,55) , StrVal(“foo”,”bar”) are: elements Nil)) (8), (I Cons (R(1.0), Cons , ,Nil) (I(8) Cons , Nil are: elements elements are: Red, Yellow, Blue Blue Yellow, Red, are: elements -

– – – –

datatypekeyval StrVal IntVal string = | intof ofstring * string * ; datatypemylistmylist of Nilvalue * = Cons | datatype value = I datatypeof ofvalueint realof= string;R S | | datatype color = Red | Yellow | datatypeBlue; color| Red = datatype = | … | | = datatype ::= | of - - - -

General form General Tagged union types union Tagged Enumeration types Enumeration

!

! !

18.09.20 Data IN3040 - 2020 ML 1 ML – IN3040 IN3040 ; can be used to define atype define canto used be to define new types define to int int * * type int_pair = (3,5); = int int = datatype int_pair a = (3,5) : : (3,5) = a a = (3,5) : : (3,5) = a int_pair a : : a a = (3,5); = a We can force the use of forcetype can abbreviation: theWe use The type inferencewill abbrev.: The not report thedefined as types

val val val val

type - > The keyword The abbreviation: We use We - > • - •

! !

18.09.20 Type abbreviations Type IN3040 - 2020 7 5 6 4 2 3 1 ML 1 ML – IN3040 IN3040 (sum) Node(5,Leaf(6), Leaf(7)) Leaf(7)) Node(5,Leaf(6), ) | sum (Node(n,t1,t2)) sum | + =sum(t1) n + sum(t2);

fun sum (Leaf sum fun n) = n datatype tree = Leaf of int | Node of int*tree*tree; of Node | = Leafint datatypetree of

- Node(4, Node(3,Leaf(1), Leaf(2)), Node(3,Leaf(1), Node(4, -

Recursive function Recursivelydefineddata structure

! !

18.09.20 Datatype and pattern matching pattern and Datatype IN3040 - 2020 ; (e2) exp * eval exp (e1) + + (e1) ML 1 ML – (v) eval | Plus of Plus | IN3040 IN3040 i var lookUp of of ) => ) => i ( Var (v) => | > string - Num Var int | 1 = > “one” “one” > = 1 | value”; “illegal => _ | | Plus(e1,e2) => => Plus(e1,e2) | | int of of : fn ) = case x of x “zero” case ) = 0 => Num = i ( ) => …) => | = i ( ) = x ; ; x ) = (v) => ….(v) => | xs exp Var … => Plus(e1,e2) Num (e) = case e of e case = (e) (x:: ; x = (x::_) bintoString hd hd bintoString eval val fun fun fun fun fun fun fun datatype - - > - - - of e case

Can also use _ in declarations if we don’t care about the value being matched Case matching is done in order Use _ to catch all missing Case expression Datatype

! ! ! ! !

18.09.20 Case expression Case IN3040 - 2020 ML 1 ML elsee::(x::xs) ; – IN3040 IN3040 | x::xs x::insert(e, =>xs) | e>x then if else e::ls ; | x::xs x::insert(e, =>xs) | e>x then if else e::ls ;

case=> nil ls [e] of

case=> nil [e]ls of | insert (e, x::xs) = if e>x then x::insert(e, xs) (e, insert x::xs) | x::insert(e, xs) =e>x then if fun insert (e: int, ls:list)(e: insert listint int, =fun int : fun insert (e,insert nil)= [e] fun fun insert (e,insert ls) fun =

3.

2. 1.

18.09.20 insert:Three ”different” declarations IN3040 - 2020 ML 1 ML – IN3040 IN3040 reference cells much as possible Restrictedto Different from other programming languages: programming other from Different expressions as separatepure side effects To from change the value of any other expression anyvalue changeother the of An expression has a value, but evaluating it does not not has expressiondoes evaluating it a value,An but

• • •

Assignment Noneofthe constructs seen so far have sideeffects

! !

18.09.20 ML imperative constructs imperative ML IN3040 - 2020 value - L value - values , called , - R R y := x+3; x+3; := y , called , and ML 1 ML – memory location contents values IN3040 IN3040 - L value) - (pseudocode, not ML!) A referencedifferentA cella valuetypea than has Explicitoperations contentsto contents orread change (declaration of identifiers) naming from “variables” Separates Identifier on right refers to refers right on Identifier storagelocationa variableA names changed be can of Contents location read, be can Identifier on left refers to a to refers left on Identifier

– – – – – – – MLcellreference (L Most languages Most Assignment Assignment

• • •

Variables Generalterminology:

Variables and assignment and Variables

! ! 18.09.20 IN3040 - 2020 x:int ML 1 ML – IN3040 IN3040 (type is “unit” since it is an expression with side effects) create cell x with initial value 0 assignable integer value integer assignable add 3 to contents of x and store result in location x location in result store and x of contents to 3 add place value of x+3 in cell x; requires x; cell in x+3 of value place - returns the contents (value) of location y location of (value) contents the returns places value x in reference cell y cell reference in x value places expression creating new cell containing value x value containing cell new creating expression non location whose contents must be integer must contents whose location > val it = 6 : int : 6 = valit > x := x+3; x := !x 3; + val x = ref 0 ; ref 0 val= x !x; > val it = () : unit unit : () = valit > - unit : () = valit > - - ref int : 0ref = valx > - y := x x := y ref x ref !y x : int ref int : y

Examples Operations Different types for location and contents and location types for Different

18.09.20

! !

! ML reference cells reference ML IN3040 - 2020 101 Bill Bob x yy ML 1 ML – IN3040 IN3040 assignable reference cell assignable not assignable (like constant otherin notassignable PL) ref y0; = ref x = ref “Bob”; = x ref int int

y := y + 1 Error! 1 + y := y val 1; + !y := y x := x “Bill”; val

x : : y - - - - -

- - Insummary: Createand increment cell Createand change contentscell

!

! !

18.09.20 ML examples ML IN3040 - 2020 i /Syllabus Pensum chapter.html - programmering level - level: level: - Funksjonell ML 1 ML : – , 1995. IN3040 IN3040 61 Kristoffersen Notes on programming SML/NJ ( : Bjørn ML for the working kompendium 1.3, 1.6, and sec. 2.) http://www.smlnj.org/ - Pucella . 1.1 Secs http://www.smlnj.org/doc/basis/pages/top standard ML;SML/NJ available types at and thetop Functions Riccardo : Norwegian:In

• • • • L.C. Paulson: Paulson: L.C.

Extra material on ML. on Extra material courseSyllabus/achievement page:” linksSee the on ” requirements

18.09.20 ! ! ! Further reading Further