440 likes | 639 Views
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.
E N D
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 • Allow the user to interactively develop formal proofs about computable functions • Created the need for a new language • ML was specifically designed for theorem proving • LCF spawned a host of successors which were all coded in ML
ML • Means Meta-Language • Created in 1973 by Robin Milner • Inspired by LISP
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
SML • Milner won the British Computer Society Award for Technical Excellence • ML was Standardized in 1990 • SML is taught as students’ first programming language at some universities
SML • Popular among compiler writers • Efficient for developing ray tracers
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
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.
Safe • ML is safe, in that a program that passes the type-checker cannot "go wrong."
Modular • The Standard ML module system supports modules (called structures) and interfaces (called signatures).
Functional • ML has higher-order functions: functions can be passed as arguments, stored in data structures, and returned as results of function calls.
Strict • Function calls in ML, like those of C, Pascal, C++, Java, etc., evaluate their arguments before entering the body of the function.
Polymorphic • ML supports polymorphic functions and data types. Such as lists of integers, lists of strings, lists of lists of integers, and so on.
Compile-time type checking • Programmers in compile-time type-checked languages get the benefit not only of faster execution but also less debugging.
Type inference • The ML programmer need not write down the type of every variable and function-parameter.
Exception handling • ML's exception-handling mechanism -- similar to the ones in C++, Java, Ada, etc. -- provides dynamic nesting of handlers.
Garbage collection • Automatic de-allocation makes programs simpler, cleaner, and more reliable.
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.
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.
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.
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.
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.
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.
Types of Macros • Set_of_abreviations::= macro_definition #macro_definition, • macro_definition_pack::= "For" #(variable ",") macro_definition #(punctuator, macro_definition),
Types of Macros • macro_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.
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.
SML Grammar • Program::= $#(Top_Level_Declaration ";" ). • Top_Level_Declaration::= Expression | Object_Declaration | Signature_Declaration | Functor_Declaration. • Object_Declaration::= Empty | Declaration | "structure" And_List( IdentO(":" Signature) "=" Structure ) | "local" Object_Declaration "in" Object_Declaration "end" | Object_DeclarationO(";") Object_Declaration. • Module::glossary=A separablycompilable unit - typically a file - containing module systems. • Module_system::glossary=Made of structure, signatures, and functors.
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_DeclarationO(";") Signature_Declaration. Signature::glossary=A collection of info describing and specifying some elements of a structure. • Signature::= "sig" Specification "end" | Ident.
SML Grammar (Continued) • Functor_Declaration::= Empty | "functor" And_List(Functor_Binding ) | Functor_DeclarationO(";") 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".
SML Grammar (Continued) • Specification::= Empty | value_spec | various_type_spec | exception_spec | structure_spec | other_spec | inclusion | SpecificationO(";") Specification. value_specification::="val" And_List(Ident ":" Type ). • various_type_spec::=("type" | "eqtype") And_List(Type_Var_ListIdent ) | "datatype" And_List(Datatype_Binding ) • exception_spec::="exception" And_List(IdentO("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 ) .
Simple SML coding examples Literals • 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
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 Functions fn 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
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")
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) orfun fib n = if n < 2 then n else fib(n-1) + fib(n-2)
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"
Strings • String in SML are like in Java • They are immutable Here 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
I/O operations in SML SML is very good with Input and Output operations And 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
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 );
Again What is Standard ML • 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. • ML main purpose was for theorem proving • ML was the first language to use polymorphism and type safe exception handling
Standard ML Mark Hull, Timothy Cronin Marc Camilien