Principles of Programming Languages

Similar documents
Principles of Programming Languages

Principles of Programming Languages

Principles of Programming Languages

Principles of Programming Languages

Programming with Universes, Generically

CS558 Programming Languages Winter 2013 Lecture 8

It turns out that races can be eliminated without sacrificing much in terms of performance or expressive power.

Lecture 7: Data Abstractions

A Practical Optional Type System for Clojure. Ambrose Bonnaire-Sergeant

CS558 Programming Languages

CSC 533: Organization of Programming Languages. Spring 2005

Denotational Semantics. Domain Theory

A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 5 Programming with Locks and Critical Sections

Storage. Outline. Variables and Updating. Composite Variables. Storables Lifetime : Programming Languages. Course slides - Storage

CSE 230 Computer Science II (Data Structure) Introduction

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Pierce Ch. 3, 8, 11, 15. Type Systems

CSE332: Data Abstractions Lecture 23: Programming with Locks and Critical Sections. Tyler Robison Summer 2010

Experimental New Directions for JavaScript

Refinement Types for TypeScript

CS321 Languages and Compiler Design I. Fall 2013 Week 8: Types Andrew Tolmach Portland State University

Storage. Outline. Variables and updating. Copy vs. Ref semantics Lifetime. Dangling References Garbage collection

CS321 Languages and Compiler Design I Winter 2012 Lecture 13

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

CS558 Programming Languages

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011

Executive Summary. It is important for a Java Programmer to understand the power and limitations of concurrent programming in Java using threads.

Software Construction

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department

CPS 506 Comparative Programming Languages. Programming Language

Today s lecture. CS 314 fall 01 C++ 1, page 1

CSCI-GA Scripting Languages

JavaScript: Sort of a Big Deal,

CPEG 852 Advanced Topics in Computing Systems The Dataflow Model of Computation

Class design guidelines. Most of this material comes from Horstmann, Cay: Object-Oriented Design & Patterns (chapter 3)

Lecture 8: Summary of Haskell course + Type Level Programming

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

This is already grossly inconvenient in present formalisms. Why do we want to make this convenient? GENERAL GOALS

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

"Object Oriented" Programming using ML

CPSC 427: Object-Oriented Programming

Data Types. (with Examples In Haskell) COMP 524: Programming Languages Srinivas Krishnan March 22, 2011

6.001 Notes: Section 8.1

Formal Semantics of Programming Languages

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

JAVA MOCK TEST JAVA MOCK TEST II

CSCI387 Data Structure Fall. Aug. 21, 2012 Sung Hee Park Computer Science Virginia State University

CS558 Programming Languages

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

Formal Semantics of Programming Languages

CSE373: Data Structure & Algorithms Lecture 23: Programming Languages. Aaron Bauer Winter 2014

CSE 20 DISCRETE MATH. Fall

[Course Overview] After completing this module you are ready to: Develop Desktop applications, Networking & Multi-threaded programs in java.

introduction to Programming in C Department of Computer Science and Engineering Lecture No. #40 Recursion Linear Recursion

Types and Programming Languages. Lecture 5. Extensions of simple types

SML Style Guide. Last Revised: 31st August 2011

+ Today. Lecture 26: Concurrency 3/31/14. n Reading. n Objectives. n Announcements. n P&C Section 7. n Race conditions.

Overview. Elements of Programming Languages. Objects. Self-Reference

CPSC 427: Object-Oriented Programming

Parametric Polymorphism for Java: A Reflective Approach

CSE 12 Abstract Syntax Trees

Syntax Analysis. Martin Sulzmann. Martin Sulzmann Syntax Analysis 1 / 38

Typed Scheme: Scheme with Static Types

D7020E. The dynamic evolution of a system Robust and Energy-Efficient Real-Time Systems. blocked Lecture 2: Components & the Timber language.

D7020E. Robust and Energy-Efficient Real-Time Systems D7020E. Lecture 2: Components & the Timber language


Case Study: Undefined Variables

CSE 20 DISCRETE MATH. Winter

Web Application Development

Pointers and Memory 1

Typed Racket: Racket with Static Types

Data Types. CSE 307 Principles of Programming Languages Stony Brook University

CSCC24 Functional Programming Scheme Part 2

Declarative concurrency. March 3, 2014

Types and Static Type Checking (Introducing Micro-Haskell)

JavaScript CS 4640 Programming Languages for Web Applications

programming languages need to be precise a regular expression is one of the following: tokens are the building blocks of programs

The story so far. Elements of Programming Languages. Pairs in various languages. Pairs

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

CS558 Programming Languages

Program Analysis: Lecture 02 Page 1 of 32

September 10,

Inheritance. Transitivity

JavaScript CS 4640 Programming Languages for Web Applications

Understanding an ADT implementation: Abstraction functions

The Case for Simple Object-Orientation in VDM++ Erik Ernst Aarhus University, Denmark

Programming with Math and Logic

CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Dan Grossman Winter 2013

Compilers and computer architecture: Semantic analysis

Overloading, Type Classes, and Algebraic Datatypes

Introducing Wybe a language for everyone

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

Data Abstraction. Hwansoo Han

Quick announcement. Midterm date is Wednesday Oct 24, 11-12pm.

Principles of Programming Languages

// the current object. functioninvocation expression. identifier (expressionlist ) // call of an inner function

Chapter 8 :: Composite Types

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

Programming Languages (PL)

Transcription:

Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Collaboration and Management Dana Fisman Lesson 5 - Data Types and Operations on Data 1

Types - what we already know Types define sets of values There are atomic and compound types The programmer can define data types and annotate its code in order to reflect the intended meaning of variables and functions A process called type checking can analyze the program to verify there are no type discrepancies 2

Types - third important role Type definitions help the programmer structure the code that operates on complex data values in a way that reflects the structure of the data type. Knowing the structure of a data type helps the programmer write correct functions that operate over values of this type. And vice versa, the decision on how to design the data type is driven by the operations that need to be preformed on them, and the desire to make them uniform. 3

Types - third important role We will illustrate this point through four examples: Homogeneous array types and the sequence interface (map, filter, reduce, ) Disjoint types and Disjoint Unions to enable uniform functional interfaces Modeling trees Mutable data types in FP 4

Homogeneous Array Types and the Sequence Interface Array values can be o homogeneous (all items are of the same types) or o heterogeneous (not all items are of the same type) The natural way to process homogenous arrays is using the sequence interface (the set of higher order functions which can be applied to them) o map o filter o reduce o and others (every, some, find, etc.) 5

Homogeneous Array Types and the Sequence Interface 6

Homogeneous Array Types and the Sequence Interface Can we always apply map(f,array) on array? When can we? When o the array is of type <SomeType>[] and o f is of type <SomeType> => <PossiblyAnotherType> 7

Homogeneous Array Types and the Sequence Interface When can we apply filter (p?,array) on array? When o the array is of type <SomeType>[] and o p? is of type <SomeType> => boolean Heterogenous arrays do not lend themselves to map etc. When can we apply reduce (f, init, array) on array? When o the array is of type <SomeType>[] and o f is of type <PossiblyOtherType>,<SomeType> => <PossiblyOtherType> o init is of type <PossiblyOtherType> 8

Creating new data types We have seen various ways to create new data types: Array types Map types Generic types We have discussed the set relations among created data types. Can we create new data types simply using set relations? Cartesian product? Union? Intersection? 9

Typescript Union and Intersection We can we create new data types simply using typescript s union and intersection type NoS = number string; type SoB = string boolean; type S = NoS & SoB; 10

Structural vs. Nominal Subtyping Compiles ok! 11 Under nominal typing (as in Java) these two types are disjoint. But sometimes we do want to distinguish these! Under structural typing (as in Javascript) these two types are equivalent.

Disjoint Types Compilation error: Type 'Person' is not assignable to type Variable'. Types of property 'tag' are incompatible. The addition of field tag caused the two types to be disjoint! 12 Does not compile as desired

Disjoint Union Mathematical definition: By combining type union operator and a mutual field (tag) with distinct values we can obtain disjoint types. 13

14 Disjoint Union

Disjoint Union 15 disjoint union together with the corresponding switch construct achieves an effect similar to sub-classes with virtual classes in OOP It allows the function to dispatch to different computations based on the type of the actual value received as a parameter.

Modeling Trees with Types The function processing the data type is structured in the same way Different fields have different assurance on their existence Using type analysis we can verify we are safe and exhaustive 16 bt = { root :2, "left":{"root":3,"left":{"root":4}}, "right":{"root":5,"right":{"root":6}}} traversedfs(bt); ==>2 3 4 5 6

Modeling Trees with Types Being exhaustive resulted in lots of repeated code 17 squaretree(bt2); ==> { root: 4, left: { root: 9, left: { root: 16 } }, right: { root: 25, right: { root: 36 } } }

Modeling Trees with Types By relaxing type checking and accepting undefined as a return value we can make the code shorter and more readable: 18

Modeling Trees with Types Output: squaretree2(bt) { root: 4, left: { root: 9, left: { root: 16, left: undefined, right: undefined }, right: undefined }, right: { root: 25, left: undefined, right: { root: 36, left: undefined, right: undefined } } } 19

Modeling Trees with Types Let us reflect on this version: The expected values of type BinTree were extended to include undefined We explicitly test for undefined as the first base case in the recursive function. The recursive calls are now simplified as we can avoid the recursive calls with a value undefined The return value has values marked explicitly as undefined - these are semantically equivalent to absent values - but in the syntax of the object, they still appear. 20

Modeling Trees with Types How can we eliminate the undefined in the output? Using JSON.stringify() The two version correspond to different styles undefined may complicate analysis but is hard to avoid 21

Mutable Data Types in FP Suppose we want to implement in FP a stack, which is mutable by nature? push(x) pop() Mutate. And return a value. empty() Query. Does not mutate. 22

Mutable Data Types in FP Let us separate to pure queries and pure mutators push(x) pop() peek() empty() Mutators Queries This definition is still inherently procedural The result maybe that even queries are not deterministic Can return different values on same calls 23

Mutable Data Types in FP Non-Functional Implementation Generic Constructor Queries. No mutations. Mutators Relies on arrays being mutable 24

Mutable Data Types in FP Can a non-deterministic behavior of queries really occur? Peek(s) on the same value s, returns different results 25

Mutable Data Types in FP Functional Implementation (not efficient) Generic Cloning utility (shallow) Constructor Queries. No mutations. Return new copy 26

Mutable Data Types in FP Does it provides a deterministic behavior? Using this implementat ion requires a change from the client side: the interface has a changed! 27 Yes! This implementation is safe But inefficient!

Mutable Data Types in FP What is the remedy? Use efficient immutable libraries such as immutable-js by Facebook 28

Mutable Data Types in FP The immutablle-js library works well with JSON So we can e.g. construct a Stack for a string 29

Summary Type definitions help the programmer structure the code that operates on complex values in a way that reflects the structure of the data type. Programmers design and name types for sets of values that will be processed by the same set of functions. Homogeneous array types encourage the programmer to consume them using the sequence interface (map, filter, reduce) 30

Summary Recursive types are processed by recursive functions othe recursive functions inspect the values according to the type definition oand can determine the base case and the inductive case. Mutable data types can be modeled in a Functional Programming style by making sure commands are written as constructors which return a new version of the values (instead of mutating an existing value). Disjoint types and Disjoint Unions enable the definition of uniform functional interfaces over types of values that are not structurally similar. 31