CITS 3242 Programming Paradigms Part II. Topic 10: Imperative Programming

Similar documents
CITS 3242 Programming Paradigms

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

Chapter 11 :: Functional Languages

Chapter 1. Preliminaries

Asynchronous Computations

Imperative programming in F#

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Chapter 1 Preliminaries

Principles of Programming Languages. Lecture Outline

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

Chapter 13: Reference. Why reference Typing Evaluation Store Typings Safety Notes

Chapter 1. Preliminaries

Mutable Data Types. Prof. Clarkson Fall A New Despair Mutability Strikes Back Return of Imperative Programming

Introduction to OCaml

G Programming Languages - Fall 2012

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

Data Structures (list, dictionary, tuples, sets, strings)

Mutation. COS 326 David Walker Princeton University

Programming Languages and Techniques (CIS120)

Ruby: Introduction, Basics

Chapter 1. Preview. Reason for Studying OPL. Language Evaluation Criteria. Programming Domains

Some Advanced ML Features

Software System Design and Implementation

Lecture Notes on Programming Languages

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

Topic 5: Examples and higher-order functions

Option Values, Arrays, Sequences, and Lazy Evaluation

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

L3 Programming September 19, OCaml Cheatsheet

CPS 506 Comparative Programming Languages. Programming Language

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

printf( Please enter another number: ); scanf( %d, &num2);

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

CSc 372. Comparative Programming Languages. 2 : Functional Programming. Department of Computer Science University of Arizona

Using Scala in CS241

G Programming Languages - Fall 2012

CMSC 330: Organization of Programming Languages. Functional Programming with OCaml

Mutation. COS 326 Andrew W. Appel Princeton University. slides copyright David Walker and Andrew W. Appel

Programming Languages and Techniques (CIS120)

CS 11 Haskell track: lecture 1

CSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem:

Consolidation and Review

CSCI-GA Scripting Languages

Haskell 98 in short! CPSC 449 Principles of Programming Languages

9/7/17. Outline. Name, Scope and Binding. Names. Introduction. Names (continued) Names (continued) In Text: Chapter 5

Expression Evaluation and Control Flow. Outline

CSCI 2041: Functions, Mutation, and Arrays

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

Computer Science 432/563 Operating Systems The College of Saint Rose Spring Topic Notes: Memory Hierarchy

Optimising Functional Programming Languages. Max Bolingbroke, Cambridge University CPRG Lectures 2010

Chapter 7. Expressions and Assignment Statements ISBN

G Programming Languages - Fall 2012

Hard deadline: 3/28/15 1:00pm. Using software development tools like source control. Understanding the environment model and type inference.

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

22c:111 Programming Language Concepts. Fall Types I

Chapter 7. Expressions and Assignment Statements

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

Programming Languages and Techniques (CIS120)

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Programovací jazyky F# a OCaml. Chapter 6. Sequence expressions and computation expressions (aka monads)

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming Language Pragmatics

Grafting Functional Support on Top of an Imperative Language

Programmiersprachen (Programming Languages)

CS 11 Ocaml track: lecture 3

First Programming Language in CS Education The Arguments for Scala

CS 11 Ocaml track: lecture 2

Chapter 15. Functional Programming Languages

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1

SNU Programming Language Theory

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Today: Revisit some objects. Programming Languages. Key data structure: Dictionaries. Using Dictionaries. CSE 130 : Winter 2009

Tomas Petricek. F# Language Overview

Polymorphism and Type Inference

CS558 Programming Languages

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Chapter 7 Expressions and Assignment statements

CS6202: Advanced Topics in Programming Languages and Systems Lecture 0 : Overview

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

Organization of Programming Languages (CSE452) Why are there so many programming languages? What makes a language successful?

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Topic 9: Type Checking

Topic 9: Type Checking

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Programming Languages and Techniques (CIS120)

Types and Type Inference

SWEN-250 Personal SE. Introduction to C

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

Functional Programming for Imperative Programmers

Scope. Chapter Ten Modern Programming Languages 1

Lectures 24 and 25: Scheduling; Introduction to Effects

Concepts of Programming Languages

CSCI312 Principles of Programming Languages!

Transcription:

CITS 3242 Programming Paradigms Part II Topic 10: Imperative Programming This topic covers the background and motivations for imperative programming, as well as the imperative constructs in F# - reference cells and mutable records. 1

Background effects in machine code The first programs were written in machine code. Machine code is just a sequence of bytes placed into memory that the circuits in the CPU directly read and execute. E.g. The bytes 53 0 123 might mean: increment memory location 123 Machine code is imperative: each instruction does something. It may modify the internal state of the machine. Or it may cause the machine to do some external action. The actions performed by an instruction are called its effects. Assembly language makes machine code easier for humans by using names for instructions instead of numbers. Eg. inc 123 Also, names can be used for locations instead of addresses. inc count (with count earlier defined as 123) 2

Imperative languages Imperative languages grew naturally from assembly language. Fortran ( formula translation ) first appeared in 1957. It made writing mathematical expressions easier than assembly Imperative languages have remained dominant since. OO grew out imperative (and functional) programming, but is still generally considered an imperative sub-paradigm. In imperative languages the emphasis is on statements and the effects that have. Imperative effects are important in this unit for two reasons: Concurrent programming generally involves sequences of effects. Seeing imperative effects in a functional context gives a new perspective. In a functional language an effect is a way that an expression affects the rest of the program, or the outside world, beyond just returning a value. 3

F# imperative programming F# includes full support for imperative programming. Mutable variables, arrays, loops, I/O, exceptions. Also.NET objects. However, a largely functional style is preferred. Functional code is generally easier to read and reason about. The functional and imperative features generally work well together when used carefully. Be careful mixing imperative code with h.o.functions. Unlike non-strict functional languages like Haskell, there is no separation between pure and imperative code. The types do not distinguish which functions have effects. This is convenient because we can easily replace a pure implementation by an imperative one. However, this can make hybrid code less structured. Also, it requires a value restriction on polymorphism Only values can be polymorphic (later). 4

Mutable reference cells Ordinary F# variables & values cannot be modified. We would like to be able to modify some vars & values, without making everything mutable. Reference cells do this by adding a type constructor for cells that hold a value that can be read and set. Operations: val ref : 'a -> 'a ref val (:=) : 'a ref -> 'a -> unit val (!) : 'a ref -> 'a > let cell1 = ref 1;; // create cell val cell1 : int ref > cell1;; val it : int ref = { contents = 1 } >!cell1;; // get contents val it : int = 1 > cell1 := 3;; // set contents val it : unit = () > cell1;; val it : int ref = { contents = 3 } >!cell1;; val it : int = 3 5

Aliasing References can be passed around, stored in lists, etc. Aliasing is when a cell a has many references to it. Aliasing can make the behaviour of code complex. Note that it is not the variable cell1 that is modified, it is the cell that it refers to. This is similar to having many references to an object. Aliasing complicates many issues in imperative programs. E.g., Fortran can be better optimized than C (due to pointers) > let cell2 = cell1;; val cell2 : int ref >!cell2;; val it : int = 3 > cell1 := 7;; val it : unit = () >!cell2;; val it : int 7 6

Records Records are basically tuples with named components called fields. Record types must be defined by giving the field names and types. type Person = { Name: string; Age: int } You can construct record values by providing a value for each field. > { Name="Bill"; Age=23 };; val it : Person = { Name="Bill"; Age=23 } You can also give the record type explicitly. > { new Person with Name = "Anna and Age=29+4 };; val it : Person = { Name="Anna"; Age=33 } The second form is useful when record types share field names. The field names are often called labels. 7

Records accessing fields. Fields of records can be accessed via patterns. > let isoldbill {Name=n; Age=a} = (n="bill" && a>21) val isoldbill : Person -> bool Some fields can be left out provided the type can be determined when labels are shared (use a constraint). > let isold{age=a} = a>21 val isold : Person -> bool Fields can also be accessed using the. notation (like Java, C) let isbill p = (p.name = "Bill") Records can be cloned to create a new record, replacing some fields. > let changename p nm = { p with Name = nm } val changename : Person -> string -> Person So far records act in a functional way, very similar to tuples. 8

Records - mutable fields Records can also have mutable fields. type DiscreteEventCounter = { mutable Total: int; mutable Positive: int; Name : string } let recordevent (s: DiscreteEventCounter) ispositive = s.total <- s.total+1 if ispositive then s.positive <- s.positive+1 In fact, reference cells are defined as records: type 'a ref = { mutable contents: 'a } let (!) r = r.contents let (:=) r v = r.contents <- v let ref v = { contents = v } You can always replace a mutable field by one having a reference type, but this may use more memory. Using reference cells rather than mutable fields is more flexible sometimes because you can extract and pass the cell itself around. 9

Reference cells vs objects & pointers A reference cell is essentially an object reference. It has one instance variable and methods for get and set. The reference is immutable it always refers to the same cell The contents of the cell/instance variable can be changed. Another view is that it is a immutable pointer. The pointer cannot be changed, but what it points to can. Consider the following example: let x : int ref = ref 3 let y : int =!x x := (!x) + 1 y + (!x) val it : int = 7 We get 7 because y is 3 and x contains 4 (Note terminology) y is 3 means that y is always 3. (Just as 3 is always 3.) Variables are just names for values in FP, and reference cells are special values which have a contents that can be changed. 10

Arrays and other imperative collections F# arrays work similarly to arrays in Java, etc. They allow modification via the operator (<-) : a[] -> a -> unit They provide fast access, but the length of an array cannot be changed > let arr = [ 1.0; 2.0; 4.0 ];; val arr : float[] > arr.[1];; val it : float = 1.0 > arr.[1] <- 3.0;; val it : unit = () > arr;; val it : float[] = [ 1.0; 3.0; 4.0 ] They can also be created via comprehensions and used in generators. > [ for x in arr -> (x,x*x) ];; val it : (float * float) array = [ (1.0, 1.0); (3.0, 9.0); (4.0, 16.0) ] The Array library contains versions of nearly all the list/seq funs. map, filter, length, append,... these work functionally, via copying. There are also functions that update arrays instead of copying. There s also 2D & 3D arrays, and.net imperative collections (subtypes of seq): resizable arrays, dictionaries (via hash tables),... 11

Input Output (I/O) I/O is another kind of imperative effects. F# mostly relies on.net libraries for I/O System.IO (files, folders, streams), System.Net (network) System.Windows.Forms (GUI), many more... However, F# has its own formatted printing in FSharp.Text.Printf printf and sprintf work like formatted printing in C, but are statically typed (via special format strings) and printfn adds a newline. %s (strings) %d (decimal) %f (float) %A (lists, tuples,...) %O (objects) Example - fetching a web page, then closing and printing: open System.IO; open System.Net let http(url: string) = let resp = System.Net.WebRequest.Create(url).GetResponse() try let reader = new StreamReader(resp.GetResponseStream()) let html = reader.readtoend() html finally printfn "Closing %s" url; resp.close() //Done even when exn. 12

Exceptions Exceptions work similarly to those in Java. Although all exceptions are unchecked, meaning that they are never included in function types, unlike Java interfaces. Also, throwing.net exceptions can be slow, even when they are caught, because the OS keeps a record of them anyway. exception BlockedURL of string let safehttp url = if url = "http://www.kaos.org" then raise(blockedurl url) else http url // Assuming fetch was previously defined. try printfn "%d" (safefetch "http://www.kaos.org").length with BlockedURL(url) -> printf "blocked! url = '%s'\n" url :? System.UriFormatException -> printfn bad url" _ -> printfn "Some other exception occurred" 13

Effects and higher-order functions Combining imperative effects and higher-order fun s requires care. Effects happen when the function causing the effects has all its arguments. Effects inside a fun are delayed, and then repeated each time the fun is applied. A semicolon (;) may be used to separate expressions so that the effects of both are done, but the result of the second is returned. let r = ref 0 let inc () = (r:=!r + 1) let id1 = (inc(); fun x -> x*2.0)!r;; // yields 1 let id2 = fun x -> (inc(); x*2.0);;!r;; // yields 1 id1 2.0;!r;; // yields 1 id2 2.0;!r;; // yields 2 let f = List.map (inc(); fun y -> y *2.0);;!r;; // yields 3 let g = List.map (fun x -> inc(); x*2.0);;!r;; // yields 3 f [1.0;2.0;3.0];!r;; // yields 3 g [1.0;2.0;3.0];!r;; // yields 6 14

Objects via records and cells Functions, records & cells allow us to roll our own objects. type point = { SetX : float -> unit; // Interface Dist : unit -> float } let point initx inity = /// Constructs point objects let x = ref initx // Instance variables (state) let y = ref inity let setx newx = (x:=newx) // Funs for methods let dist () = sqrt (!x *!x +!y*!y) {SetX = setx; Dist = dist} // Package into a record object let p = point 2.0 3.0 p.setx 4.0 p.dist() val it : float = 5.0 // Construct an object // Call it s methods The state is hidden, and can only be accessed via the methods We can also roll similar sorts of structures in F#, as we choose This was roughly how people experimented with early objects 15