lecture 2 3 standard ml
play

Lecture 2/3 : Standard ML A type-safe language that embodies many - PowerPoint PPT Presentation

CS6202: Advanced Topics in Programming Languages and Systems Lecture 2/3 : Standard ML A type-safe language that embodies many innovative ideas in language design. CS6202 ML 1 Standard ML Standard ML Great programming language


  1. CS6202: Advanced Topics in Programming Languages and Systems Lecture 2/3 : Standard ML A type-safe language that embodies many innovative ideas in language design. CS6202 ML 1

  2. Standard ML Standard ML • Great programming language – reusability, abstraction, quite efficient. • Expression-Oriented. • Values, Types and Effects • Polymorphic Types and Inference • Products, Records and Algebraic Types • Higher-Order Functions • Exceptions and Reference Types • Rich Module Language Reference --- Programming in Standard ML: http://www.cs.cmu.edu/~rwh/introsml/ CS6202 ML 2

  3. Example ML Program Example ML Program • Problem – matching string against a regular expression. • Structure is implementation , while signature denotes interface . CS6202 ML 3

  4. Signature Signature • Signature – describe interface of modules. • Signature Expression : sigexp ::= sig specs end • Contains basic specifications for type, datatype, exception, values. • Signature binding : signature sigid = sigexp CS6202 ML 4

  5. Implementation Implementation • Implementation of signature is called structure. • Components referred by long identifiers. CS6202 ML 5

  6. Structure Structure • A unit of program with declarations for types, exceptions and values. • Structure Expression : strexp ::= struct decs end • Contains definitions for type, datatype, exception, values. • Structure binding : structure strid = strexp CS6202 ML 6

  7. Computation Model Computation Model • Emphasis is on evaluation of expressions rather than 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. • 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

  8. Values Values • Expression has a type, denoted by exp : typ • Can be evaluated to a value, denoted by exp ⇓ val CS6202 ML 8

  9. Types Types • Some examples of base types : CS6202 ML 9

  10. Declarations Declarations • 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 10

  11. Limiting Scope Limiting Scope • Scope of a type variable or type constructor may be delimited, as follows : • An Example. CS6202 ML 11

  12. Functions Functions • Two main aspects : • algorithmic – how it is computed • extensional – what is being computed • Each function has a type : typ -> typ’ • Anonymous function written using syntax : Example : CS6202 ML 12

  13. Functions Functions • Function is also a value : • An example of function value : CS6202 ML 13

  14. Tuple and Product Type and Product Type Tuple • Aggregate data structures, such as tuples, lists, can be easily created and manipulated. • An n-tuple is a finite ordered sequence : : product type tuple value Example CS6202 ML 14

  15. Tuple Pattern Pattern Tuple • Allows easy access of components. General form : • Permitted form of tuple pattern : • Example : CS6202 ML 15

  16. Record Types Record Types • Record type allows a label to be associated with each component. • A record value and its type : : record type record value • Record binding. CS6202 ML 16

  17. Record Example Record Example record binding record type ellipsis as shorthand expanded CS6202 ML 17

  18. Selectors Selectors • A list of predefined selection function for the i-th component of a tuple. • Predefined selector for record fields : • Use sparingly as patterns are typically clearer. CS6202 ML 18

  19. Case Analysis Case Analysis • Clausal function expression useful for cases. • An example : • Alternative form : ≡ CS6202 ML 19

  20. Recursive Function Recursive Function • Use rec to indicate recursive value binding. • Or use fun notation directly : CS6202 ML 20

  21. General Recursion General Recursion • Requires linear stack space. • Example : CS6202 ML 21

  22. Iteration via Tail- -Recursion Recursion Iteration via Tail • Loop is equivalent to tail-recursive code • Example : • What is a tail call, and why is it more efficient? CS6202 ML 22

  23. Polymorphism / Overloading Polymorphism / Overloading • Some functions have generic type. For example, the identity function has a principal type ‘a -> ‘a • Overloading uses the same name for a class of operator. • Hard problem: CS6202 ML 23

  24. Algebraic Data Types Algebraic Data Types • Data type declaration via datatype contains : • Type constructor • Value constructor(s) • Examples of non-recursive data types. type constructor value constructors CS6202 ML 24

  25. Algebraic Data Types Algebraic Data Types • Some may have type parameters, e.g. • An example of its use : • Recursive type is also possible : CS6202 ML 25

  26. Algebraic Data Types Algebraic Data Types • Recursive functions : • Mutual recursive data types (a bit contrived): • Disjoint union types : CS6202 ML 26

  27. Abstract Syntax Tree Abstract Syntax Tree • Easy to model symbolic data structures : • An interpreter : CS6202 ML 27

  28. Lists Lists • A built-in data type with 2 value constructors. abbreviated • Some functions on list : infix version of append CS6202 ML 28

  29. Higher- -Order Functions Order Functions Higher • Functions are first-class : pass as arguments , return as result , contain inside data structures , has a type . • Key main uses : • abstracting control • staging computation • Example – applies a function to every element of list CS6202 ML 29

  30. Higher- -Order Functions Order Functions Higher • Returning function as result : • Curry function to untupled argument tupled curried CS6202 ML 30

  31. Abstracting Control Abstracting Control • Abstracting similar patterns of control • What is the principal type of this reduction? CS6202 ML 31

  32. Staging Staging • Distinguish early from late arguments : early argument late argument • Improve by early evaluation and then sharing. staged_append [v 1 ,…,v n ] CS6202 ML 32

  33. Exceptions Exceptions • Are useful to catch runtime errors. • An example of user-defined exception : CS6202 ML 33

  34. Exceptions Exceptions • Exception handler can be used to catch a raised exception. This can make software more robust. • Handler has the syntax: exp handle match match ::= pat => exp CS6202 ML 34

  35. Exceptions Exceptions • Exception can implement back-tracking. • Exception may carry values. declare raise catch CS6202 ML 35

  36. Mutable Store Mutable Store • 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 : • How is equality implemented for reference? CS6202 ML 36

  37. Bad Imperative Programming Bad Imperative Programming • A factorial function : can you follow? CS6202 ML 37

  38. OO Programming Style OO Programming Style • An single counter : • A class of counters : type of new_counter CS6202 ML 38

  39. Mutable Array Mutable Array • Mutable array as a primitive data structure : • 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

  40. Memoization Memoization • Repeated calls are retrieved rather than recomputed. CS6202 ML 40

  41. Memoization Memoization • Apply the same idea to computing fibonacci efficiently. local val limit : int = 1000 val memo : int option array = Array.array(limit,NONE) in fun fib’ 0 = 1 | fib’ 1 = 1 | fib’ n = fib(n-1) + fib(n-2) and fib n = if n<limit then case Array.sub (memo,n) of SOMR r => r | None => let r=fib’ n in Array.update(memo,n,SOME r) end else fib’ n end CS6202 ML 41

  42. Tupling Tupling • Is there no hope for purity? Use tupled function fibtup n = (fib(n+1), fib(n)) Optimised code with reuse : fun fibtup 0 = (1,1) | fibtup n = case fibtup(n-1) of (u,v) => (u+v,u) and fib n = snd(fibtup(n)) end More optimization – tail recursion ? logarithmic time? CS6202 ML 42

  43. Input/Output Input/Output • Standard input/output organized as streams. • Read a line from an input stream. inputLine : instream -> string • Write a line to stdout stream. print : string -> unit • Write a line to a specific stream. 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

  44. Lazy Data Structures Lazy Data Structures • ML philosophy – laziness us a special case of eagerness. Can treat an unevaluated expression as a value. • Applications (i) infinite structures (e.g. streams) (ii) interactive system activate SML/NJ option (iii) better termination property • Infinite stream and acceses: 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