standard ml

44
Standard ML Mark Hull, Timothy Cronin Marc Camilien

Upload: taji

Post on 05-Jan-2016

26 views

Category:

Documents


1 download

DESCRIPTION

Standard ML. Mark Hull, Timothy Cronin Marc Camilien . Summary. History Standard ML Overview Syntax and Examples. LCF. Logic for Computable Functions Proposed by Dana Scott in 1969 Developed by Robin Milner at the University of Edinburg. LCF. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Standard ML

Standard ML

Mark Hull,Timothy CroninMarc Camilien 

Page 2: Standard ML

Summary

HistoryStandard ML OverviewSyntax and Examples

Page 3: Standard ML

LCF

Logic for Computable Functions

Proposed by Dana Scott in 1969

Developed by Robin Milner at the University of Edinburg

Page 4: Standard ML

LCF

Allow the user to interactively develop formal proofs about computable functions

Created the need for a new languageML was specifically designed for

theorem provingLCF spawned a host of successors which

were all coded in ML

Page 5: Standard ML

ML

Means Meta-LanguageCreated in 1973 by Robin Milner

Inspired by LISP

Page 6: Standard ML

ML

First language to use polymorphic type inference

First language to use type-safe exception handling

ML influenced HOPE Robin Milner led the standardization

effort to consolidate HOPE and ML

Page 7: Standard ML

SML

Milner won the British Computer Society Award for Technical Excellence

ML was Standardized in 1990SML is taught as students’ first programming language at some universities

Page 8: Standard ML

SML

Popular among compiler writers

Efficient for developing ray tracers

Page 9: Standard ML
Page 10: Standard ML

C++:

struct Scene { virtual ~Scene() {}; ... };

struct Sphere : public Scene { Vec center; double radius; Sphere(Vec c, double r) : center(c), radius(r) {} ~ Sphere() {} ... };

typedef list<Scene *> Scenes;

struct Group : public Scene { Sphere bound; Scenes child; Group(Sphere b, Scenes c) : bound(b), child(c) {} ~Group() { for (Scenes::const_iterator it=child.begin(); it != child.end(); ++it) delete *it; } ... };

SML:

datatype scene = Sphere | Group of (scene * vec * real) list

Page 11: Standard ML
Page 12: Standard ML

What is Standard ML (SML)Standard ML is a safe, modular, functional,

strict, polymorphic programming language with compile-time type checking and type inference, exception handling, garbage collection, immutable data types, abstract data types, and parametric modules. It has efficient implementations and a formal definition.

Page 13: Standard ML

Safe•ML is safe, in that a program that passes the type-checker cannot "go wrong."

Page 14: Standard ML

Modular•The Standard ML module system supports modules (called structures) and interfaces (called signatures).

Page 15: Standard ML

Functional•ML has higher-order functions: functions can be passed as arguments, stored in data structures, and returned as results of function calls.

Page 16: Standard ML

Strict•Function calls in ML, like those of C, Pascal, C++, Java, etc., evaluate their arguments before entering the body of the function.

Page 17: Standard ML

Polymorphic•ML supports polymorphic functions and data types. Such as lists of integers, lists of strings, lists of lists of integers, and so on.

Page 18: Standard ML

Compile-time type checking•Programmers in compile-time type-checked languages get the benefit not only of faster execution but also less debugging.

Page 19: Standard ML

Type inference•The ML programmer need not write down the type of every variable and function-parameter.

Page 20: Standard ML

Exception handling•ML's exception-handling mechanism -- similar to the ones in C++, Java, Ada, etc. -- provides dynamic nesting of handlers.

Page 21: Standard ML

Garbage collection•Automatic de-allocation makes programs simpler, cleaner, and more reliable.

Page 22: Standard ML

Immutable data types•In ML, most variables and data structures are immutable. Tends to build new data structures (and let the old ones be garbage collected) instead of modifying old ones.

Page 23: Standard ML

Abstract data types•ML supports information hiding, so that one can implement a data type whose representation is hidden by an interface that just exports functions to construct and operate on the type.

Page 24: Standard ML

Parametric modules•A functor is an ML program module that takes the signature of another module as an argument. The functor can then be applied to any module matching that signature. This leads to better program modularity.

Page 25: Standard ML

Efficient implementations•Features such as polymorphism, parametric modules, and a heavy reliance on garbage collection have meant that compiling ML to efficient machine code requires techniques not usually necessary in C compilers. Several Standard ML compilers generate high-quality machine code, including Standard ML of New Jersey and Harlequin ML Works.

Page 26: Standard ML

Formal definition•The ML language is clearly specified by The Definition of Standard ML (Revised) (Milner, Tofte, Harper, MacQueen, MIT Press, 1997), which defines the language in 93 pages of mathematical notation and English prose.

Page 27: Standard ML

Macros

Macros are a useful technique for describing languages, and if used correctly leave the complexity of the processor unchanged.

Functions that map sets of strings into sets of strings can be used as macros. If they are not recursive and defined with the same formula as any other definition then they can be removed. They can be treated as 'macros' or abbreviations.

Page 28: Standard ML

Types of Macros

Set_of_abreviations::= macro_definition #macro_definition,

macro_definition_pack::= "For" #(variable ",") macro_definition #(punctuator, macro_definition),

Page 29: Standard ML

Types of Macrosmacro_definition::= name "(" bound_symbol

#("," bound_symbol)")" "::= " regular_expression(element=>(string|variable)) The expressions in the above may not use macros, etc.

macro_reference::= name "(" expression #("," expression)")" There are the same number of expressions in a macro_reference as symbols in the macro_definition.

Page 30: Standard ML

Notes on meta-notation

Empty::="". -- the null string.O(...) encloses an optional phrase so O(A)::=(A|Empty).$#(A) - zero or more occurences of A, and N(A) - one or more occurrences of A,

so #(A)::= O(N(A)). N(A)::= (A) $#(A).L(A, B) encloses a repetitive phrase of the form ABABA...BA -- 1 or more

repetitions of A, separated by B. L(A,B)::= A $#(B A). List(A)::=L(A, ",")= A $#("," A). And_List(A)::=L(A, "and") = A $#("and" A). Sequence(A)::=L(A, ";") = A $#(";" A). O_List(A)::= O(List(A))::=An optional List of A's.

Page 31: Standard ML

SML Grammar

• Program::= $#(Top_Level_Declaration ";" ). • Top_Level_Declaration::= Expression |

Object_Declaration | Signature_Declaration | Functor_Declaration.

• Object_Declaration::= Empty | Declaration | "structure" And_List( Ident O(":" Signature) "=" Structure ) | "local" Object_Declaration "in" Object_Declaration "end" | Object_Declaration O(";") Object_Declaration.

• Module::glossary=A separably compilable unit - typically a file - containing module systems.

• Module_system::glossary=Made of structure, signatures, and functors.

Page 32: Standard ML

SML Grammar (Continued)Structure::glossary=a collection of types,

datatypes, functions, exceptions, etc we wish to encapsulate.

Signature_Declaration::= Empty | "signature" And_List(Ident "=" Signature ) | Signature_Declaration O(";") Signature_Declaration. Signature::glossary=A collection of info describing and specifying some elements of a structure.

Signature::= "sig" Specification "end" | Ident.

Page 33: Standard ML

SML Grammar (Continued)

Functor_Declaration::= Empty | "functor" And_List(Functor_Binding ) | Functor_Declaration O(";") Functor_Declaration. Functor::Glossary=An Operation that takes one or more structures and produces another one. The ML Functor meets the same need to generate special cases of code from a general form that generics do in Ada and templates do in C++.

Functor_Binding::= Ident "(" Functor_Arguments ")" O(":" Signature) "=" Structure.

Functor_Arguments::= Ident ":" Signature | Specification. Functor_Application::= Ident "(" Structure | Sequence(

structure_declaration) ")". Structure::= "struct" Object_Declaration "end" | Compound_Ident

| Functor_Application | Ident "(" Object_Declaration ")" | "let" Object_Declaration "in" Structure "end".

Page 34: Standard ML

SML Grammar (Continued)

Specification::= Empty | value_spec | various_type_spec | exception_spec | structure_spec | other_spec | inclusion | Specification O(";") Specification. value_specification::="val" And_List(Ident ":" Type ).

various_type_spec::=("type" | "eqtype") And_List(Type_Var_List Ident ) | "datatype" And_List(Datatype_Binding )

exception_spec::="exception" And_List(Ident O("of" Type) ). structure_spec::="structure" And_List(Ident ":" Signature ) other_spec::="sharing" And_List( O("type") Ident "=" L(Ident

, "=") ) | "local" Specification "in" Specification "end" | "open" L(Compound_Ident ).

inclusions::= "include" N(Ident ) .

Page 35: Standard ML

Simple SML coding examplesLiterals- 3;

> val it = 3 : int - - 3.141;

> val it = 3.141 : real - - "Hello world";

> val it = "Hello world" : string - - #"J";

> val it = #"J" : char - - true;

> val it = true : bool - - ();

> val it = () : unit - - [1,2,3];

> val it = [1, 2, 3] : int list - - #[1,2,3];

> val it = #[1, 2, 3] : int vector

-Standard does not have vector literals but most implementations support them – use library functions otherwise -Does not have array literals – use library functions

Page 36: Standard ML

Simple SML coding examples (continued)• Expressions~3*(1+7) div 2 mod 3 ~1.0/2.0 + 1.9*x a orelse b andalso c

Functionsfn f => fn x => fn y => f(x,y) fn 0 => 0

 | n => 1 f o g map SOME xs map #2 triples

map #lab records

Page 37: Standard ML

Simple SML coding examples (continued)Sequential Logic (if-else; while… SML does

not have a for loop)if 3 > 2 then "X" else "Y" if 3 > 2 then print "hello" else ()

Does not have for loops - use recursion or while

(print "Hello ";  print "world")

Page 38: Standard ML

Simple SML coding examples (continued)Value/Type Declarations

val name = expr

fun f x y = expr

val rec fib = fn n =>    if n < 2    then n    else fib(n-1) + fib(n-2) or fun fib n =    if n < 2    then n    else fib(n-1) + fib(n-2)

Page 39: Standard ML

Simple SML coding examples (continued)type t = int -> bool

type ('a,'b) assoc_list = ('a * 'b) list

datatype 'a option = NONE | SOME of 'a

datatype complex = C of real * real fun complex xy = C xy fun coord (C xy) = xy

type foo = {x:int, y:float, s:string ref} //record typesNote: record types do not need to be declared

val bar = {x=0, y=3.14, s=ref ""}

#x bar #y bar !(#s bar)

//assignment to a record

#s bar := "something"

Page 40: Standard ML

Strings• String in SML are like in Java• They are immutableHere are a couple of String Functions"Hello " ^ "world" Int.toString 13

Real.toString 3.141 String.size s String.substring(s, 1, 2) String.sub(s, 0)

REMINDER: Strings are immutable, use CharArray for mutability

Page 41: Standard ML

I/O operations in SML

SML is very good with Input and Output operationsAnd even has its own I/O functions included. They do,

however, differ from the ones we are used to…Here is a sample I/O operation command in SML.fun copyFile(name1, name2) =

   let       val file1 = TextIO.openIn name1       val s     = TextIO.inputAll file1       val _     = TextIO.closeIn file1       val file2 = TextIO.openOut name2    in       TextIO.output(file2, s);       TextIO.closeOut file2    end

Page 42: Standard ML

A function we all know…“Hello World” in Standard ML

fun main (cmd:string, args:string list):OS.Process.status =

( print "Hello world\n"; 0 );

Page 43: Standard ML

Again What is Standard MLStandard ML is a safe, modular, functional,

strict, polymorphic programming language with compile-time type checking and type inference, exception handling, garbage collection, immutable data types, abstract data types, and parametric modules. It has efficient implementations and a formal definition.

ML main purpose was for theorem provingML was the first language to use polymorphism

and type safe exception handling

Page 44: Standard ML

Standard ML

Mark Hull,Timothy CroninMarc Camilien