lecture 2 3 standard ml
play

Lecture 2/3 : Standard ML Great programming language reusability, - PowerPoint PPT Presentation

CS6202: Advanced Topics in Standard ML Standard ML Programming Languages and Systems Lecture 2/3 : Standard ML Great programming language reusability, abstraction, quite efficient. Expression-Oriented. Values, Types and


  1. CS6202: Advanced Topics in Standard ML Standard ML Programming Languages and Systems Lecture 2/3 : Standard ML • Great programming language – reusability, abstraction, quite efficient. • Expression-Oriented. • Values, Types and Effects A type-safe language that embodies • Polymorphic Types and Inference many innovative ideas in language • Products, Records and Algebraic Types design. • Higher-Order Functions • Exceptions and Reference Types • Rich Module Language Reference --- Programming in Standard ML: http://www.cs.cmu.edu/~rwh/introsml/ CS6202 ML 1 CS6202 ML 2 Example ML Program Example ML Program Signature Signature • Problem – matching string against a regular expression. • Signature – describe interface of modules. • Signature Expression : sigexp ::= sig specs end • Contains basic specifications for type, datatype, exception, values. • Signature binding : signature sigid = sigexp • Structure is implementation , while signature denotes interface . CS6202 ML 3 CS6202 ML 4

  2. Implementation Structure Implementation Structure • Implementation of signature is called structure. • A unit of program with declarations for types, exceptions and values. • Structure Expression : strexp ::= struct decs end • Components referred by long identifiers. • Contains definitions for type, datatype, exception, values. • Structure binding : structure strid = strexp CS6202 ML 5 CS6202 ML 6 Computation Model Computation Model Values Values • Emphasis is on evaluation of expressions rather than • Expression has a type, denoted by exp : typ command. • Each expression has three characteristics : (i) type , (ii) value and (iii) possible effect . • Type is a description of the value it is supposed to yield. • Can be evaluated to a value, denoted by exp ⇓ val • Evaluation may cause an effect, such as input/output , exception or mutation . • Pure expression (e.g. mathematical functions) does not have side-effects. CS6202 ML 7 CS6202 ML 8

  3. Types Declarations Types Declarations • Some examples of base types : • Any type may be given a name through type binding • A value may be given a name through a value binding. Such bindings are type-checked, and rejected if ill-typed. CS6202 ML 9 CS6202 ML 10 Limiting Scope Limiting Scope Functions Functions • Two main aspects : • Scope of a type variable or type constructor may be • algorithmic – how it is computed delimited, as follows : • extensional – what is being computed • Each function has a type : typ -> typ’ • An Example. • Anonymous function written using syntax : Example : CS6202 ML 11 CS6202 ML 12

  4. Functions Tuple and Product Type and Product Type Functions Tuple • Function is also a value : • Aggregate data structures, such as tuples, lists, can be easily created and manipulated. • An n-tuple is a finite ordered sequence : : • An example of function value : product type tuple value Example CS6202 ML 13 CS6202 ML 14 Tuple Pattern Tuple Pattern Record Types Record Types • Allows easy access of components. General form : • Record type allows a label to be associated with each component. • A record value and its type : • Permitted form of tuple pattern : : record type record value • Record binding. • Example : CS6202 ML 15 CS6202 ML 16

  5. Record Example Selectors Record Example Selectors record binding • A list of predefined selection function for the i-th record type component of a tuple. • Predefined selector for record fields : ellipsis as shorthand expanded • Use sparingly as patterns are typically clearer. CS6202 ML 17 CS6202 ML 18 Case Analysis Case Analysis Recursive Function Recursive Function • Clausal function expression useful for cases. • Use rec to indicate recursive value binding. • An example : • Or use fun notation directly : • Alternative form : ≡ CS6202 ML 19 CS6202 ML 20

  6. General Recursion Iteration via Tail- -Recursion Recursion General Recursion Iteration via Tail • Requires linear stack space. • Loop is equivalent to tail-recursive code • Example : • Example : • What is a tail call, and why is it more efficient? CS6202 ML 21 CS6202 ML 22 Algebraic Data Types Algebraic Data Types Polymorphism / Overloading Polymorphism / Overloading • Some functions have generic type. For example, the • Data type declaration via datatype contains : identity function has a principal type ‘a -> ‘a • Type constructor • Value constructor(s) • Examples of non-recursive data types. • Overloading uses the same name for a class of operator. type constructor value constructors • Hard problem: CS6202 ML 23 CS6202 ML 24

  7. Algebraic Data Types Algebraic Data Types Algebraic Data Types Algebraic Data Types • Some may have type parameters, e.g. • Recursive functions : • An example of its use : • Mutual recursive data types (a bit contrived): • Recursive type is also possible : • Disjoint union types : CS6202 ML 25 CS6202 ML 26 Abstract Syntax Tree Lists Abstract Syntax Tree Lists • Easy to model symbolic data structures : • A built-in data type with 2 value constructors. abbreviated • An interpreter : • Some functions on list : infix version of append CS6202 ML 27 CS6202 ML 28

  8. Higher Higher- -Order Functions Order Functions Higher- Higher -Order Functions Order Functions • Functions are first-class : pass as arguments , return as • Returning function as result : result , contain inside data structures , has a type . • Key main uses : • abstracting control • Curry function to untupled argument • staging computation • Example – applies a function to every element of list tupled curried CS6202 ML 29 CS6202 ML 30 Abstracting Control Staging Abstracting Control Staging • Distinguish early from late arguments : • Abstracting similar patterns of control early argument late argument • Improve by early evaluation and then sharing. staged_append [v 1 ,…,v n ] • What is the principal type of this reduction? CS6202 ML 31 CS6202 ML 32

  9. Exceptions Exceptions Exceptions Exceptions • Are useful to catch runtime errors. • Exception handler can be used to catch a raised exception. This can make software more robust. • An example of user-defined exception : • Handler has the syntax: exp handle match match ::= pat => exp CS6202 ML 33 CS6202 ML 34 Exceptions Mutable Store Exceptions Mutable Store • Exception can implement back-tracking. • Mutable cell contains a value that may change : • Create a mutable cell with an initial value : ref : ‘a -> ‘a ref • Contents can be retrieved using : ! : ‘a ref -> ‘a Can use a ref pattern : • Exception may carry values. • How is equality implemented for reference? declare raise catch CS6202 ML 35 CS6202 ML 36

  10. Bad Imperative Programming Bad Imperative Programming OO Programming Style OO Programming Style • A factorial function : can you follow? • An single counter : • A class of counters : type of new_counter CS6202 ML 37 CS6202 ML 38 Mutable Array Memoization Mutable Array Memoization • Mutable array as a primitive data structure : • Repeated calls are retrieved rather than recomputed. • Can be used for memoization where many redundant calls, e.g n-th Catalan number : sum f n = (f 0) + … + (f n) CS6202 ML 39 CS6202 ML 40

  11. Memoization Memoization Tupling Tupling • Apply the same idea to computing fibonacci efficiently. • Is there no hope for purity? Use tupled function local val limit : int = 1000 fibtup n = (fib(n+1), fib(n)) val memo : int option array = Array.array(limit,NONE) in fun fib’ 0 = 1 Optimised code with reuse : | fib’ 1 = 1 | fib’ n = fib(n-1) + fib(n-2) and fib n = fun fibtup 0 = (1,1) if n<limit then | fibtup n = case fibtup(n-1) of case Array.sub (memo,n) of (u,v) => (u+v,u) SOMR r => r and fib n = snd(fibtup(n)) | None => let r=fib’ n in end Array.update(memo,n,SOME r) end More optimization – tail recursion ? logarithmic time? else fib’ n end CS6202 ML 41 CS6202 ML 42 Input/Output Lazy Data Structures Input/Output Lazy Data Structures • Standard input/output organized as streams. • ML philosophy – laziness us a special case of eagerness. Can treat an unevaluated expression as a value. • Read a line from an input stream. • Applications (i) infinite structures (e.g. streams) inputLine : instream -> string (ii) interactive system activate SML/NJ option (iii) better termination property • Write a line to stdout stream. print : string -> unit • Write a line to a specific stream. • Infinite stream and acceses: output : outstream * string -> unit flushout : outstream -> unit • A blocking input that reads current available string input : instream -> string • Non-blocking input that reads upto n-char string caninput : instream * int -> string CS6202 ML 43 CS6202 ML 44

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend