GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing en.wikipedia.org — Standard ML - Wikipedia
Standard ML (SML) is a general-purpose, high-level, modular, functional programming language with compile-time type checking and type inference. It is popular for writing compilers, for programming language research, and for developing theorem provers. It was created by Robert Harper. Standard ML is a modern dialect of ML, the language used in the Logic for Computable Functions (LCF) theorem-proving project. It is distinctive among widely used languages in that it has a formal specification, given as typing rules and operational semantics in The Definition of Standard ML, originally released in 1990, with a second and final revision being released in 1997.[5][6] Language
Standard ML is a functional programming language with some impure features.[7] Programs written in Standard ML consist of expressions in contrast to statements or commands, although some expressions of type unit are only evaluated for their side-effects. FunctionsLike all functional languages, a key feature of Standard ML is the function, which is used for abstraction. The factorial function can be expressed as follows: fun factorial n = if n = 0 then 1 else n * factorial (n - 1) Type inferenceAn SML compiler must infer the static type Declarative definitionsThe same function can be expressed with clausal function definitions where the if-then-else conditional is replaced with templates of the factorial function evaluated for specific values: fun factorial 0 = 1 | factorial n = n * factorial (n - 1) Imperative definitionsor iteratively: fun factorial n = let val i = ref n and acc = ref 1 in while !i > 0 do (acc := !acc * !i; i := !i - 1); !acc end Lambda functionsor as a lambda function: val rec factorial = fn 0 => 1 | n => n * factorial (n - 1) Here, the keyword Local definitionsThe encapsulation of an invariant-preserving tail-recursive tight loop with one or more accumulator parameters within an invariant-free outer function, as seen here, is a common idiom in Standard ML. Using a local function, it can be rewritten in a more efficient tail-recursive style: local fun loop (0, acc) = acc | loop (m, acc) = loop (m - 1, m * acc) in fun factorial n = loop (n, 1) end Type synonymsA type synonym is defined with the keyword type loc = real * real fun square (x : real) = x * x fun dist (x, y) (x', y') = Math.sqrt (square (x' - x) + square (y' - y)) fun heron (a, b, c) = let val x = dist a b val y = dist b c val z = dist a c val s = (x + y + z) / 2.0 in Math.sqrt (s * (s - x) * (s - y) * (s - z)) end Algebraic datatypesStandard ML provides strong support for algebraic datatypes (ADT). A data type can be thought of as a disjoint union of tuples (or a "sum of products"). They are easy to define and easy to use, largely because of pattern matching, and most Standard ML implementations' pattern-exhaustiveness checking and pattern redundancy checking. In object-oriented programming languages, a disjoint union can be expressed as class hierarchies. However, in contrast to class hierarchies, ADTs are closed. Thus, the extensibility of ADTs is orthogonal to the extensibility of class hierarchies. Class hierarchies can be extended with new subclasses which implement the same interface, while the functions of ADTs can be extended for the fixed set of constructors. See expression problem. A datatype is defined with the keyword datatype shape = Circle of loc * real (* center and radius *) | Square of loc * real (* upper-left corner and side length; axis-aligned *) | Triangle of loc * loc * loc (* corners *) Note that a type synonym cannot be recursive; datatypes are necessary to define recursive constructors. (This is not at issue in this example.) Pattern matchingPatterns are matched in the order in which they are defined. C programmers can use tagged unions, dispatching on tag values, to do what ML does with datatypes and pattern matching. Nevertheless, while a C program decorated with appropriate checks will, in a sense, be as robust as the corresponding ML program, those checks will of necessity be dynamic; ML's static checks provide strong guarantees about the correctness of the program at compile time. Function arguments can be defined as patterns as follows: fun area (Circle (_, r)) = Math.pi * square r | area (Square (_, s)) = square s | area (Triangle p) = heron p (* see above *) The so-called "clausal form" of function definition, where arguments are defined as patterns, is merely syntactic sugar for a case expression: fun area shape = case shape of Circle (_, r) => Math.pi * square r | Square (_, s) => square s | Triangle p => heron p Exhaustiveness checkingPattern-exhaustiveness checking will make sure that each constructor of the datatype is matched by at least one pattern. The following pattern is not exhaustive: fun center (Circle (c, _)) = c | center (Square ((x, y), s)) = (x + s / 2.0, y + s / 2.0) There is no pattern for the Redundancy checkingThe pattern in the second clause of the following (meaningless) function is redundant: fun f (Circle ((x, y), r)) = x + y | f (Circle _) = 1.0 | f _ = 0.0 Any value that would match the pattern in the second clause would also match the pattern in the first clause, so the second clause is unreachable. Therefore, this definition as a whole exhibits redundancy, and causes a compile-time warning. The following function definition is exhaustive and not redundant: val hasCorners = fn (Circle _) => false | _ => true If control gets past the first pattern ( Higher-order functionsFunctions can consume functions as arguments: fun map f (x, y) = (f x, f y) Functions can produce functions as return values: fun constant k = (fn _ => k) Functions can also both consume and produce functions: fun compose (f, g) = (fn x => f (g x)) The function fun map _ [] = [] | map f (x :: xs) = f x :: map f xs A more efficient implementation with tail-recursive fun map f = List.rev o List.foldl (fn (x, acc) => f x :: acc) [] ExceptionsExceptions are raised with the keyword local exception Zero; val p = fn (0, _) => raise Zero | (a, b) => a * b in fun prod xs = List.foldl p 1 xs handle Zero => 0 end When The same optimization can be obtained with a tail call. local fun p a (0 :: _) = 0 | p a (x :: xs) = p (a * x) xs | p a [] = a in val prod = p 1 end Module systemStandard ML's advanced module system allows programs to be decomposed into hierarchically organized structures of logically related type and value definitions. Modules provide not only namespace control but also abstraction, in the sense that they allow the definition of abstract data types. Three main syntactic constructs comprise the module system: signatures, structures and functors. SignaturesA signature is an interface, usually thought of as a type for a structure; it specifies the names of all entities provided by the structure, the arity of each type component, the type of each value component, and the signature of each substructure. The definitions of type components are optional; type components whose definitions are hidden are abstract types. For example, the signature for a queue may be: signature QUEUE = sig type 'a queue exception QueueError; val empty : 'a queue val isEmpty : 'a queue -> bool val singleton : 'a -> 'a queue val fromList : 'a list -> 'a queue val insert : 'a * 'a queue -> 'a queue val peek : 'a queue -> 'a val remove : 'a queue -> 'a * 'a queue end This signature describes a module that provides a polymorphic type StructuresA structure is a module; it consists of a collection of types, exceptions, values and structures (called substructures) packaged together into a logical unit. A queue structure can be implemented as follows: structure TwoListQueue :> QUEUE = struct type 'a queue = 'a list * 'a list exception QueueError; val empty = ([], []) fun isEmpty ([], []) = true | isEmpty _ = false fun singleton a = ([], [a]) fun fromList a = ([], a) fun insert (a, ([], [])) = singleton a | insert (a, (ins, outs)) = (a :: ins, outs) fun peek (_, []) = raise QueueError | peek (ins, outs) = List.hd outs fun remove (_, []) = raise QueueError | remove (ins, [a]) = (a, ([], List.rev ins)) | remove (ins, a :: outs) = (a, (ins, outs)) end This definition declares that The types and values in a structure can be accessed with "dot notation": val q : string TwoListQueue.queue = TwoListQueue.empty val q' = TwoListQueue.insert (Real.toString Math.pi, q) FunctorsA functor is a function from structures to structures; that is, a functor accepts one or more arguments, which are usually structures of a given signature, and produces a structure as its result. Functors are used to implement generic data structures and algorithms. One popular algorithm for breadth-first search of trees makes use of queues.[8] Here is a version of that algorithm parameterized over an abstract queue structure: (* after Okasaki, ICFP, 2000 *) functor BFS (Q: QUEUE) = struct datatype 'a tree = E | T of 'a * 'a tree * 'a tree local fun bfsQ q = if Q.isEmpty q then [] else search (Q.remove q) and search (E, q) = bfsQ q | search (T (x, l, r), q) = x :: bfsQ (insert (insert q l) r) and insert q a = Q.insert (a, q) in fun bfs t = bfsQ (Q.singleton t) end end structure QueueBFS = BFS (TwoListQueue) Within Code examplesWikibooks has a book on the topic of: Standard ML Programming
Snippets of SML code are most easily studied by entering them into an interactive top-level. Hello, world!The following is a "Hello, World!" program:
AlgorithmsInsertion sortInsertion sort for fun insert (x, []) = [x] | insert (x, h :: t) = sort x (h, t) and sort x (h, t) = if x < h then [x, h] @ t else h :: insert (x, t) val insertionsort = List.foldl insert [] MergesortMain article: Merge sort
Here, the classic mergesort algorithm is implemented in three functions: split, merge and mergesort. Also note the absence of types, with the exception of the syntax Split
fun alternator {} = let val state = ref true in fn a => !state before state := not (!state) end (* Split a list into near-halves which will either be the same length, * or the first will have one more element than the other. * Runs in O(n) time, where n = |xs|. *) fun split xs = List.partition (alternator {}) xs Merge Merge uses a local function loop for efficiency. The inner This function merges two sorted lists into one sorted list. Note how the accumulator (* Merge two ordered lists using the order cmp. * Pre: each list must already be ordered per cmp. * Runs in O(n) time, where n = |xs| + |ys|. *) fun merge cmp (xs, []) = xs | merge cmp (xs, y :: ys) = let fun loop (a, acc) (xs, []) = List.revAppend (a :: acc, xs) | loop (a, acc) (xs, y :: ys) = if cmp (a, y) then loop (y, a :: acc) (ys, xs) else loop (a, y :: acc) (xs, ys) in loop (y, []) (ys, xs) end Mergesort The main function: fun ap f (x, y) = (f x, f y) (* Sort a list in according to the given ordering operation cmp. * Runs in O(n log n) time, where n = |xs|. *) fun mergesort cmp [] = [] | mergesort cmp [x] = [x] | mergesort cmp xs = (merge cmp o ap (mergesort cmp) o split) xs QuicksortMain article: Quicksort
Quicksort can be expressed as follows. infix << fun quicksort (op <<) = let fun part p = List.partition (fn x => x << p) fun sort [] = [] | sort (p :: xs) = join p (part p xs) and join p (l, r) = sort l @ p :: sort r in sort end Expression interpreterNote the relative ease with which a small expression language can be defined and processed: exception TyErr; datatype ty = IntTy | BoolTy fun unify (IntTy, IntTy) = IntTy | unify (BoolTy, BoolTy) = BoolTy | unify (_, _) = raise TyErr datatype exp = True | False | Int of int | Not of exp | Add of exp * exp | If of exp * exp * exp fun infer True = BoolTy | infer False = BoolTy | infer (Int _) = IntTy | infer (Not e) = (assert e BoolTy; BoolTy) | infer (Add (a, b)) = (assert a IntTy; assert b IntTy; IntTy) | infer (If (e, t, f)) = (assert e BoolTy; unify (infer t, infer f)) and assert e t = unify (infer e, t) fun eval True = True | eval False = False | eval (Int n) = Int n | eval (Not e) = if eval e = True then False else True | eval (Add (a, b)) = (case (eval a, eval b) of (Int x, Int y) => Int (x + y)) | eval (If (e, t, f)) = eval (if eval e = True then t else f) fun run e = (infer e; SOME (eval e)) handle TyErr => NONE Example usage on well-typed and ill-typed expressions: val SOME (Int 3) = run (Add (Int 1, Int 2)) (* well-typed *) val NONE = run (If (Not (Int 1), True, False)) (* ill-typed *) Arbitrary-precision integersThe The following program implements an arbitrary-precision factorial function:
Partial applicationCurried functions have many applications, such as eliminating redundant code. For example, a module may require functions of type In this example, - fun d delta f x = (f (x + delta) - f (x - delta)) / (2.0 * delta) val d = fn : real -> (real -> real) -> real -> real The type of - val d' = d 1E~8; val d' = fn : (real -> real) -> real -> real The inferred type indicates that - d' (fn x => x * x * x - x - 1.0) 3.0; val it = 25.9999996644 : real LibrariesStandardThe Basis Library[9] has been standardized and ships with most implementations. It provides modules for trees, arrays, and other data structures, and input/output and system interfaces. Third partyFor numerical computing, a Matrix module exists (but is currently broken), https://www.cs.cmu.edu/afs/cs/project/pscico/pscico/src/matrix/README.html. For graphics, cairo-sml is an open source interface to the Cairo graphics library. For machine learning, a library for graphical models exists. ImplementationsImplementations of Standard ML include the following: Standard
Derivative
Research
All of these implementations are open-source and freely available. Most are implemented themselves in Standard ML. There are no longer any commercial implementations; Harlequin, now defunct, once produced a commercial IDE and compiler called MLWorks which passed on to Xanalys and was later open-sourced after it was acquired by Ravenbrook Limited on April 26, 2013. Major projects using SMLThe IT University of Copenhagen's entire enterprise architecture is implemented in around 100,000 lines of SML, including staff records, payroll, course administration and feedback, student project management, and web-based self-service interfaces.[10] The proof assistants HOL4, Isabelle, LEGO, and Twelf are written in Standard ML. It is also used by compiler writers and integrated circuit designers such as ARM.[11] See alsoReferences
External linksAbout Standard ML
About successor ML
Practical Academic Hidden categories:
| ||||||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. | ||||||||||||||||||||||||||||||||||||||||||||||||||||