CSE 341 Lecture 12 structures Ullman 8 - 8.2 slides created by Marty Stepp

Slides:



Advertisements
Similar presentations
Programming with Lists
Advertisements

ML Lists.1 Standard ML Lists. ML Lists.2 Lists A list is a finite sequence of elements. [3,5,9] ["a", "list" ] [] Elements may appear more than once [3,4]
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  Elements may appear more than once.
ML Exceptions.1 Standard ML Exceptions. ML Exceptions.2 Exceptions – The Need  An extensive part of the code is error handling  A function can return.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
F28PL1 Programming Languages Lecture 14: Standard ML 4.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  ML lists are immutable.  Elements.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Maths & Trig, Statistical functions. ABS Returns the absolute value of a number The absolute value of a number is the number without its sign Syntax ◦
ML Exceptions.1 Standard ML Exceptions. ML Exceptions.2 Exceptions – The Need  An extensive part of the code is error handling  A function F can return.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Winter 2013.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
CSE 341 Lecture 16 More Scheme: lists; helpers; let/let*; higher-order functions; lambdas slides created by Marty Stepp
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Chapter ElevenModern Programming Languages1 A Fourth Look At ML.
ML Exceptions.1 Standard ML Exceptions. ML Exceptions.2 Exceptions – The Need  An extensive part of the code is error handling  A function can return.
CSE 143 Lecture 18 Binary Trees read slides created by Marty Stepp and Hélène Martin
CSE341: Programming Languages Lecture 12 Modules Dan Grossman Fall 2011.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
6.1 JavaScript Objects and Object- Oriented Programming (OOP)
Crash course on SML Wojciech Moczydłowski SML – functional programming language Complete formal semantics Extremely convenient for writing compilers, interpreters,
FORTRAN.  Fortran or FORmula TRANslation was developed in the 1950's by IBM as an alternative to Assembly Language. First successfull high level language.
Abstract Data Type (ADT). 2 An Abstract Data Type (ADT) is a data structure with a set of operations –Operations specify how the ADT behaves, but does.
Cse321, Programming Languages and Compilers 1 7/14/2015 Lecture #3b, Jan. 22, 2007 References While Loops Accumulating parameter functions Regular Expressions.
CSE 143 Lecture 19 Binary Search Trees read 17.3 slides created by Marty Stepp
CSE 341 Lecture 10 more about data types; nullable types; option Ullman ; slides created by Marty Stepp
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.
COSC 1P03 Data Structures and Abstraction 4.1 Abstract Data Types The advantage of a bad memory is that one enjoys several times the same good things for.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Operators, Functions and Modules1 Pattern Matching & Recursion.
F28PL1 Programming Languages Lecture 15: Standard ML 5.
Modules and Decomposition UW CSE 190p Summer 2012 download examples from the calendar.
CSE 143 Lecture 20 Binary Search Trees continued; Tree Sets read slides created by Marty Stepp and Hélène Martin
CSC 107 – Programming For Science. Announcements  Lectures may not cover all material from book  Material that is most difficult or challenging is focus.
Chapter 9: Functional Programming in a Typed Language.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Cpt S 223 – Advanced Data Structures Math Review 2
CSE 143 Lecture 21 Binary Search Trees, continued read slides created by Marty Stepp
CSE 3302 Programming Languages Chengkai Li, Weimin He Spring 2008 Abstract Data Types and Modules Lecture 11 – ADT and Modules, Spring CSE3302 Programming.
Cs776(Prasad)L112Modules1 Modules value : type : function :: structure : signature : functor.
CSE 341 : Programming Languages Lecture 12 ML Modules Zach Tatlock Spring 2014.
CSE 341 Lecture 8 curried functions Ullman 5.5 slides created by Marty Stepp
CSE 143 Lecture 20 Binary Search Trees read 17.3 slides created by Marty Stepp
CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Spring 2013.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
CSE 110: Programming Language I Afroza Sultana UB 1230.
CSE 143 Lecture 20 Binary Search Trees continued; Tree Sets
CSE341: Programming Languages Lecture 10 ML Modules
ML: a quasi-functional language with strong typing
Functions and patterns
CSE 341 Lecture 20 Mutation; memoization slides created by Marty Stepp
slides created by Marty Stepp
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Spring 2013.
PROGRAMMING IN HASKELL
CSE341: Programming Languages Lecture 10 ML Modules
CSE 341 Lecture 3 let expressions; pattern matching Ullman
CSE341: Programming Languages Lecture 10 ML Modules
CSE 341 Section 5 Winter 2018.
CSE341: Programming Languages Lecture 10 ML Modules
Functions, Patterns and Datatypes
Fundamentals of Functional Programming
Binary Search Trees continued; Tree Sets
CSE341: Programming Languages Lecture 10 ML Modules
CSE 341 Lecture 7 anonymous functions; composition of functions Ullman 5.1.3, 5.6 slides created by Marty Stepp
Functions and patterns
CSE341: Programming Languages Lecture 10 ML Modules
CSE341: Programming Languages Lecture 10 ML Modules
Presentation transcript:

CSE 341 Lecture 12 structures Ullman slides created by Marty Stepp

2 Modules module: A separate, self-contained, reusable, interchangeable software component.  basis of the idea of modular programming ML's module system includes:  structures(like classes)  signatures(like interfaces)  functors(like parameterized class factories)

3 Why modules? organization: puts related code together decomposition: break down a problem information hiding / encapsulation: protect data from damage by other code group identifiers into namespaces; reduce # of globals provide a layer of abstraction; allows re-implementation ability to rigidly enforce data invariants provides a discrete unit for testing

4 Structure syntax structure name = struct definitions end; a structure can contain: function definitions val declarations (variables; class constants) exceptions type definitions and datatypes

5 Structure example (* Functions and data types for binary search trees of integers. *) structure IntTree = struct datatype intTree = Empty | Node of int * intTree * intTree; (* Adds the given value to the tree in order. Produces/returns the new state of the tree node after the add. *) fun add(Empty, value) = Node(value, Empty, Empty) | add(n as Node(data, left, right), value) = if value < data then Node(data, add(left, value), right) else if value > data then Node(data, left, add(right, value)) else n; (* duplicate; no change *) (* Produces the height of the given tree. An Empty tree has a height of 0. *) fun height(Empty) = 0 | height(Node(_, left, right)) = 1 + Int.max(height(left), height(right)); (* Produces the smallest value in the tree, if the tree has any data. *) fun min(Node(data, Empty, right)) = SOME data | min(Node(data, left, right)) = min(left) | min(Empty) = NONE; end;

6 Using a structure structure.member val t1 = IntTree.add(IntTree.Empty, 42); val t2 = IntTree.add(t1, 27); val mn = IntTree.min(t2); structure members such as add and Empty are no longer part of the global namespace

7 Importing a structure's contents open structure; open IntTree; val t1 = add(Empty, 42); val t2 = add(t1, 27); val mn = min(t2); if you open a structure, its members are brought into the global namespace and can be used without a prefix  + : shorter client code  - : namespace pollution / confusion (e.g. with Int.min )

8 ML's built-in structures structmembers (partial) Int int minInt maxInt abs min max toString +-* Real real precision +-*/ abs min max compare floor ceil trunc round toString fromString Char char ord chr isAscii isDigit toLower toUpper isSpace String string size sub concat explode tokens compare ^ Bool bool not toString fromString :: hd tl null length nth take getItem rev concat append map find filter partition foldl foldr exists all

9 More built-in structures structmembers (partial) Option option isSome valOf getOpt compose join General unit exn (exceptions) order ! := o before ignore Math pi e sqrt sin cos tan asin acos atan pow ln log10 IntInf divMod pow log2 orb xorb andb notb > TextIO openIn openOut print inputLine stdIn stdOut stdErr OS.Process status success failure exit getEnv sleep others Date Time Timer Array Vector Socket CommandLine

10 Structure exercise Define a structure Rational to represent rational numbers, i.e., fractions.  It can be a whole number, or a numerator/denominator.  Define an add function to add two rational numbers.  Define a toString method to produce a rational string.  Don't worry (yet) about the notion of reducing fractions.

11 Structure solution (* initial version of Rational structure that shows how to group a datatype, constructors, and functions into a single unit. *) structure Rational = struct datatype rational = Whole of int | Fraction of int * int; fun add(Whole i, Whole j) = Whole(i + j) | add(Whole i, Fraction(j, k)) = Fraction(j + k * i, k) | add(Fraction(j, k), Whole i) = Fraction(j + k * i, k) | add(Fraction(a, b), Fraction(c, d)) = Fraction(a*d + b*c, b*d); fun toString(Whole i) = Int.toString(i) | toString(Fraction(a, b)) = Int.toString(a) ^ "/" ^ Int.toString(b); end;

12 Structure exercise 2 Improve the Rational structure by adding features:  Prohibit rational numbers that have a denominator of 0.  Represent all rational numbers in reduced form. –e.g. instead of 4/12, store 1/3. –make use of Euclid's formula for greatest common divisors: fun gcd(a, 0) = abs(a) | gcd(a, b) = gcd(b, a mod b)

13 Structure solution 2 (* Includes gcd/reduce and 'new' function to guarantee invariants *) structure Rational = struct datatype rational = Whole of int | Fraction of int * int; exception Undefined; fun gcd(a, 0) = abs(a) | gcd(a, b) = gcd(b, a mod b); fun reduce(Whole(i)) = Whole(i) | reduce(Fraction(a, b)) = let val d = gcd(a, b) in if b = d then Whole(a div d) else Fraction(a div d, b div d) end; fun new(a, 0) = raise Undefined (* constructs a fraction *) | new(a, b) = reduce(Fraction(a, b)); fun add(Whole(i), Whole(j)) = Whole(i + j) | add(Whole(i), Fraction(c, d)) = Fraction(i*d + c, d) | add(Fraction(a, b), Whole(j)) = Fraction(a + j*b, b) | add(Fraction(a, b), Fraction(c, d)) = reduce(Fraction(a*d + c*b, b*d)); (* toString unchanged *) end;

14 The order datatype datatype order = LESS | EQUAL | GREATER; part of ML standard basis library used to indicate whether one value is than other  can be used when defining natural orderings for types many structures (Int, Real, String, etc.) define a compare method that returns a value of type order  some also implement, >= operators based on it, but overloaded operators don't work well on structures

15 Order example (* Includes gcd/reduce and 'new' function to guarantee invariants *) structure Rational = struct datatype rational = Whole of int | Fraction of int * int;... fun compare(Whole(a), Whole(b)) = Int.compare(a, b) | compare(Fraction(a, b), Whole(c)) = Int.compare(a, c*b) | compare(Whole(c), Fraction(a, b)) = Int.compare(a, c*b) | compare(Fraction(a,b), Fraction(c,d)) = Int.compare(a*d, c*b) end;