Functional Programming First Class Functions, Lambdas and Closures

Total Page:16

File Type:pdf, Size:1020Kb

Functional Programming First Class Functions, Lambdas and Closures Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Functional Programming First class functions, lambdas and closures Radu Nicolescu Department of Computer Science University of Auckland 23 July 2018 1 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java 1 Programming paradigms 2 Pure FP 3 Recursion 4 C# Delegates 5 Lambda expressions 6 Closures 7 More Lambdas 8 Quiz { Simple scenarios 9 Lambdas in Javascript 10 Lambdas in Java 2 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Programming paradigms • Object-oriented: develop complex objects starting with simple objects (using inheritance, aggregation, delegation, ...) • Functional: develop complex functions starting with simple functions (using function composition, Kleisli, ...) • Object-oriented or functional? • Object-oriented and functional! More dimensions, more tools! • Most modern languages evolve towards a multi-paradigm style • Object-first: C#, Java, C++, ... • Functional-first: F#, Javascript (Lisp in Java syntax), ... • Object-functional: Scala, ... 4 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Side-bar: functions and methods • In classical OOP, functions only appear as methods: • Static/class methods • Instance methods (cf. this pointer) • Other languages, including FP, have standalone, even top-level, functions • Problem: how to represent anonymous inline functions (such as lambdas) in OOP? • Solution: embed these in the current object, if possible, or inside hidden automatically constructed objects { more at closures 5 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Basic ingredients of FP • first-class and higher order functions (aka, functionals) • informally, you can work with functions as with any other objects { and compose them! • you can have functions that take functions as parameters and return functions (functions which may be dynamically composed) • currying or partial application of functions • memoization (or caching) of function results • no side effects and immutable values (next slide) 6 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Pure FP • Function results should only depend on parameter values • No side effects: Functions should not change the global state or any persistent state (unlike object methods which change the object's state) • Immutable values: Ideally, functions should not change any value at all! { This is possible if we use recursion instead of classical loops... • As one of the advantages, programs will be easier to prove correct, to optimize or to parallelize 8 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Pure FP • For example, if f and g don't change any global variable nor any of their parameters (i.e., a; b; c; d), the following two statements can run in parallel, on a dual-core machine: 1 x=f(a,b); | function f could be evaluated on core #1 2 3 y=g(c,d); | function g could be evaluated on core #2 • However, many practical languages, including C# (and F#), do accept side effects, although some of them will try to explicit or localize these (e.g., via so-called monads) 9 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Variables and mutability in C# • Class fields and properties : vast topic, but not much of our concern here... • var or normal declarations are mutable 1 var x=10; x=x+1; 2 i n t x=10; x=x+1; • const defines compile-time immutable values 1 const x = 1 0 ; • readonly defines run-time immutable fields { maybe differently initialised in constructors, but then is frozen 1 readonly int x ; 10 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Variables and mutability in C# • Shallow vs deep immutability • Shallow immutable complex objects such as arrays 1 c l a s s C f 2 public static readonly int []A 3 = new i n t [] f 10 , 20 , 30 , g ; 4 g 5 6 void Main ( ) f 7 var B = new i n t [] f 100, 200, 300, g ; 8 // C .A = B; // NOT allowed 9 C .A [ 1 ] = 200; // allowed! 10 C .A. Dump ( ) ; 11 g • Conclusions: flexible but porous 11 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Variables and mutability in F# • Class fields and properties : vast topic, but not much of our concern here... • let declarations are immutable { not \variables" but values 1 l e t x = 10 • x = x + 1 is legal (!) but does NOT mean what one would think: it is a boolean equality test that returns false ! • Mutable variables must be explicitly declared so 1 l e t mutable x = 10 2 x <− x + 1 • Increased awareness: the assignment to a mutable variable uses a distinct op sign <− 12 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Variables and mutability in F# • Still shallow immutable arrays (but not other objects) 1 l e t A = [ j 1 0 ; 2 0 ; 3 0 ; j ] // A itself is immutable 2 A . [ 1 ] <− 200 // allowed! 3 A. Dump ( ) • Why this exception for arrays? Because of the HUGE body of scientific algorithms, which have been developed and optimised for FORTRAN mutable arrays • F# encourages a more pure style, and promotes increased awareness of mutability { but still allows one the choice to use other styles 13 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Variables and mutability in JS • var declarations are mutable with global scope or function \global" scope 1 var x = 10 • let declarations are mutable with block local scope 1 i f ( b ) f 2 l e t x = 10 3 x = x + 1 4 g • const declarations are immutable with block local scope 1 i f ( b ) f 2 const x = 10 3 // x = x + 1 // not allowed 4 g • More in part (M) 14 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Imperative factorial • F# 1 l e t f a c t n : i n t = 2 l e t mutable m = n 3 l e t mutable f = 1 4 while (m >= 1) do 5 f <− f ∗ m 6 m <− m − 1 7 f 8 9 p r i n t f n "Imperative: %A" (fact 5) 16 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Naive recursive factorial • F# 1 l e t rec f a c t ' n = 2 i f n <= 0 then 1 3 e l s e ( f a c t ' ( n−1)) ∗ n 4 5 p r i n t f n "Naive Recursive: %A" (fact ' 5) • Performance issues, stack overflow 17 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Tail recursive factorial • F# 1 l e t f a c t ' ' n = 2 l e t rec f a c t tailrec n acc = 3 i f ( n <= 0) then acc 4 e l s e f a c t t a i l r e c ( n−1) ( n∗ acc ) 5 f a c t t a i l r e c n 1 6 7 p r i n t f n "Tail Recursive: %A" (fact '' 5) • F# : TCO = Tail Call Optimisation • NO performance issues, NO stack overflow 18 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Tail recursive factorial { reverse engineered • C# : recursion ) while loop! 1 s t a t i c i n t f a c t t a i l r e c ( i n t n , i n t acc ) f 2 while ( n > 0) f 3 acc = n ∗ acc ; 4 n = n − 1 ; 5 g 6 return acc ; 7 g 8 public static int f a c t ( i n t n ) f 9 return f a c t tailrec(n, 1); 10 g • NO performance issues, NO stack overflow 19 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java C# Delegates in a nutshell • Consider this scenario 1 c l a s s C f 2 p u b l i c i n t F( i n t x ) f return x +1; g 3 p u b l i c i n t G( i n t y ) f return y+y ; g 4 public static int H( i n t z ) f return z ∗ z ; g 5 g • What do these three methods have in common? • Their signature: int!int • Usage (assuming using static System.Console) 1 WriteLine ($"f c1 . F (3)g f c2 .G(3)g fC .H(3)g "); 2 // 4 6 9 21 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java C# Delegates in a nutshell • Same scenario 1 c l a s s C f 2 p u b l i c i n t F( i n t x ) f return x +1; g 3 p u b l i c i n t G( i n t y ) f return y+y ; g 4 public static int H( i n t z ) f return z ∗ z ; g 5 g • More flexible usage using typed function pointers! 1 Func <int , int > f = c1 . F ; 2 Func <int , int > g = c2 .G; 3 Func <int , int > h = C .H; 4 WriteLine ($"f f (3)g fg (3)g fh (3)g "); 5 // 4 6 9 • The same pointer, e.g. f, could point in turn to all these methods! 22 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java C# Delegates • A delegate is a .NET type-safe pointer to a function, i.e. to a class or instance method • To call an instance method: obj.F (...) • To call a static method: Class .H (...) • Technically, a delegate is an object with two properties • Method: a pointer to the instance or class method (F,H) • Target { for instance methods: pointer to actual object (obj) • instance method calls depend on the actual target object • Target { for static methods: null (usually) • static methods can be fully resolved by the compiler (so the actual class is not needed at runtime) 23 / 61 Paradigms Pure Rec Delegates Lambdas Closures More QuizJS Java Predefined delegate types in C# { Function types in F# 1 Func<T1,T2,..
Recommended publications
  • Lecture 4. Higher-Order Functions Functional Programming
    Lecture 4. Higher-order functions Functional Programming [Faculty of Science Information and Computing Sciences] 0 I function call and return as only control-flow primitive I no loops, break, continue, goto I (almost) unique types I no inheritance hell I high-level declarative data-structures I no explicit reference-based data structures Goal of typed purely functional programming Keep programs easy to reason about by I data-flow only through function arguments and return values I no hidden data-flow through mutable variables/state [Faculty of Science Information and Computing Sciences] 1 I (almost) unique types I no inheritance hell I high-level declarative data-structures I no explicit reference-based data structures Goal of typed purely functional programming Keep programs easy to reason about by I data-flow only through function arguments and return values I no hidden data-flow through mutable variables/state I function call and return as only control-flow primitive I no loops, break, continue, goto [Faculty of Science Information and Computing Sciences] 1 I high-level declarative data-structures I no explicit reference-based data structures Goal of typed purely functional programming Keep programs easy to reason about by I data-flow only through function arguments and return values I no hidden data-flow through mutable variables/state I function call and return as only control-flow primitive I no loops, break, continue, goto I (almost) unique types I no inheritance hell [Faculty of Science Information and Computing Sciences] 1 Goal
    [Show full text]
  • Higher-Order Functions 15-150: Principles of Functional Programming – Lecture 13
    Higher-order Functions 15-150: Principles of Functional Programming { Lecture 13 Giselle Reis By now you might feel like you have a pretty good idea of what is going on in functional program- ming, but in reality we have used only a fragment of the language. In this lecture we see what more we can do and what gives the name functional to this paradigm. Let's take a step back and look at ML's typing system: we have basic types (such as int, string, etc.), tuples of types (t*t' ) and functions of a type to a type (t ->t' ). In a grammar style (where α is a basic type): τ ::= α j τ ∗ τ j τ ! τ What types allowed by this grammar have we not used so far? Well, we could, for instance, have a function below a tuple. Or even a function within a function, couldn't we? The following are completely valid types: int*(int -> int) int ->(int -> int) (int -> int) -> int The first one is a pair in which the first element is an integer and the second one is a function from integers to integers. The second one is a function from integers to functions (which have type int -> int). The third type is a function from functions to integers. The two last types are examples of higher-order functions1, i.e., a function which: • receives a function as a parameter; or • returns a function. Functions can be used like any other value. They are first-class citizens. Maybe this seems strange at first, but I am sure you have used higher-order functions before without noticing it.
    [Show full text]
  • Clojure, Given the Pun on Closure, Representing Anything Specific
    dynamic, functional programming for the JVM “It (the logo) was designed by my brother, Tom Hickey. “It I wanted to involve c (c#), l (lisp) and j (java). I don't think we ever really discussed the colors Once I came up with Clojure, given the pun on closure, representing anything specific. I always vaguely the available domains and vast emptiness of the thought of them as earth and sky.” - Rich Hickey googlespace, it was an easy decision..” - Rich Hickey Mark Volkmann [email protected] Functional Programming (FP) In the spirit of saying OO is is ... encapsulation, inheritance and polymorphism ... • Pure Functions • produce results that only depend on inputs, not any global state • do not have side effects such as Real applications need some changing global state, file I/O or database updates side effects, but they should be clearly identified and isolated. • First Class Functions • can be held in variables • can be passed to and returned from other functions • Higher Order Functions • functions that do one or both of these: • accept other functions as arguments and execute them zero or more times • return another function 2 ... FP is ... Closures • main use is to pass • special functions that retain access to variables a block of code that were in their scope when the closure was created to a function • Partial Application • ability to create new functions from existing ones that take fewer arguments • Currying • transforming a function of n arguments into a chain of n one argument functions • Continuations ability to save execution state and return to it later think browser • back button 3 ..
    [Show full text]
  • Topic 6: Partial Application, Function Composition and Type Classes
    Recommended Exercises and Readings Topic 6: Partial Application, • From Haskell: The craft of functional programming (3rd Ed.) Function Composition and Type • Exercises: • 11.11, 11.12 Classes • 12.30, 12.31, 12.32, 12.33, 12.34, 12.35 • 13.1, 13.2, 13.3, 13.4, 13.7, 13.8, 13.9, 13.11 • If you have time: 12.37, 12.38, 12.39, 12.40, 12.41, 12.42 • Readings: • Chapter 11.3, and 11.4 • Chapter 12.5 • Chapter 13.1, 13.2, 13.3 and 13.4 1 2 Functional Forms Curried and Uncurried Forms • The parameters to a function can be viewed in two different ways • Uncurried form • As a single combined unit • Parameters are bundled into a tuple and passed as a group • All values are passed as one tuple • Can be used in Haskell • How we typically think about parameter passing in Java, C++, Python, Pascal, C#, … • Typically only when there is a specific need to do • As a sequence of values that are passed one at a time • As each value is passed, a new function is formed that requires one fewer parameters • Curried form than its predecessor • Parameters are passed to a function sequentially • How parameters are passed in Haskell • Standard form in Haskell • But it’s not a detail that we need to concentrate on except when we want to make use of it • Functions can be transformed from one form to the other 3 4 Curried and Uncurried Forms Curried and Uncurried Forms • A function in curried form • Why use curried form? • Permits partial application multiply :: Int ‐> Int ‐> Int • Standard way to define functions in Haskell multiply x y = x * y • A function of n+1
    [Show full text]
  • Assignment 6: Subtyping and Bidirectional Typing
    Assignment 6: Subtyping and Bidirectional Typing 15-312: Foundations of Programming Languages Joshua Dunfield ([email protected]) Out: Thursday, October 24, 2002 Due: Thursday, November 7 (11:59:59 pm) 100 points total + (up to) 20 points extra credit 1 Introduction In this assignment, you will implement a bidirectional typechecker for MinML with , , +, 1, 0, , , and subtyping with base types int and float. ! ∗ 8 9 Note: In the .sml files, most changes from Assignment 4 are indicated like this: (* new asst6 code: *) ... (* end asst6 code *) 2 New in this assignment Some things have become obsolete (and have either been removed or left • in a semi-supported state). Exceptions and continuations are no longer “officially” supported. One can now (and sometimes must!) write type annotations e : τ. The • abstract syntax constructor is called Anno. The lexer supports shell-style comments in .mml source files: any line • beginning with # is ignored. There are now two valid syntaxes for functions, the old syntax fun f (x:t1):t2 is e end • and a new syntax fun f(x) is e end. Note the lack of type anno- tations. The definition of the abstract syntax constructor Fun has been changed; its arguments are now just bindings for f and x and the body. It no longer takes two types. 1 The old syntax fun f(x:t1):t2 is e end is now just syntactic sugar, transformed by the parser into fun f(x) is e end : t1 -> t2. There are floating point numbers, written as in SML. There is a new set of • arithmetic operators +., -., *., ˜.
    [Show full text]
  • (901133) Instructor: Eng
    home Al-Albayt University Computer Science Department C++ Programming 1 (901133) Instructor: Eng. Rami Jaradat [email protected] 1 home Subjects 1. Introduction to C++ Programming 2. Control Structures 3. Functions 4. Arrays 5. Pointers 6. Strings 2 home 1 - Introduction to C++ Programming 3 home What is computer? • Computers are programmable devices capable of performing computations and making logical decisions. • Computers can store, retrieve, and process data according to a list of instructions • Hardware is the physical part of the compute: keyboard, screen, mouse, disks, memory, and processing units • Software is a collection of computer programs, procedures and documentation that perform some tasks on a computer system 4 home Computer Logical Units • Input unit – obtains information (data) from input devices • Output unit – outputs information to output device or to control other devices. • Memory unit – Rapid access, low capacity, stores information • Secondary storage unit – cheap, long-term, high-capacity storage, stores inactive programs • Arithmetic and logic unit (ALU) – performs arithmetic calculations and logic decisions • Central processing unit (CPU): – supervises and coordinates the other sections of the computer 5 home Computer language • Machine languages: machine dependent, it consists of strings of numbers giving machine specific instructions: +1300042774 +1400593419 +1200274027 • Assembly languages: English-like abbreviations representing elementary operations, assemblers convert assembly language to machine
    [Show full text]
  • Functional Programming Lecture 1: Introduction
    Functional Programming Lecture 13: FP in the Real World Viliam Lisý Artificial Intelligence Center Department of Computer Science FEE, Czech Technical University in Prague [email protected] 1 Mixed paradigm languages Functional programming is great easy parallelism and concurrency referential transparency, encapsulation compact declarative code Imperative programming is great more convenient I/O better performance in certain tasks There is no reason not to combine paradigms 2 3 Source: Wikipedia 4 Scala Quite popular with industry Multi-paradigm language • simple parallelism/concurrency • able to build enterprise solutions Runs on JVM 5 Scala vs. Haskell • Adam Szlachta's slides 6 Is Java 8 a Functional Language? Based on: https://jlordiales.me/2014/11/01/overview-java-8/ Functional language first class functions higher order functions pure functions (referential transparency) recursion closures currying and partial application 7 First class functions Previously, you could pass only classes in Java File[] directories = new File(".").listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }); Java 8 has the concept of method reference File[] directories = new File(".").listFiles(File::isDirectory); 8 Lambdas Sometimes we want a single-purpose function File[] csvFiles = new File(".").listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getAbsolutePath().endsWith("csv"); } }); Java 8 has lambda functions for that File[] csvFiles = new File(".")
    [Show full text]
  • Notes on Functional Programming with Haskell
    Notes on Functional Programming with Haskell H. Conrad Cunningham [email protected] Multiparadigm Software Architecture Group Department of Computer and Information Science University of Mississippi 201 Weir Hall University, Mississippi 38677 USA Fall Semester 2014 Copyright c 1994, 1995, 1997, 2003, 2007, 2010, 2014 by H. Conrad Cunningham Permission to copy and use this document for educational or research purposes of a non-commercial nature is hereby granted provided that this copyright notice is retained on all copies. All other rights are reserved by the author. H. Conrad Cunningham, D.Sc. Professor and Chair Department of Computer and Information Science University of Mississippi 201 Weir Hall University, Mississippi 38677 USA [email protected] PREFACE TO 1995 EDITION I wrote this set of lecture notes for use in the course Functional Programming (CSCI 555) that I teach in the Department of Computer and Information Science at the Uni- versity of Mississippi. The course is open to advanced undergraduates and beginning graduate students. The first version of these notes were written as a part of my preparation for the fall semester 1993 offering of the course. This version reflects some restructuring and revision done for the fall 1994 offering of the course|or after completion of the class. For these classes, I used the following resources: Textbook { Richard Bird and Philip Wadler. Introduction to Functional Program- ming, Prentice Hall International, 1988 [2]. These notes more or less cover the material from chapters 1 through 6 plus selected material from chapters 7 through 9. Software { Gofer interpreter version 2.30 (2.28 in 1993) written by Mark P.
    [Show full text]
  • Explicitly Implicifying Explicit Constructors
    Explicitly Implicifying explicit Constructors Document number: P1163R0 Date: 2018-08-31 Project: Programming Language C++, Library Working Group Reply-to: Nevin “☺” Liber, [email protected] or [email protected] Table of Contents Revision History ................................................................................................................ 3 P11630R0 .................................................................................................................................... 3 Introduction ....................................................................................................................... 4 Motivation and Scope ....................................................................................................... 5 Impact On the Standard ................................................................................................... 6 Policy .................................................................................................................................. 7 Design Decisions ................................................................................................................ 8 Technical Specifications ................................................................................................... 9 [template.bitset]........................................................................................................................ 10 [bitset.cons] ..............................................................................................................................
    [Show full text]
  • Currying and Partial Application and Other Tasty Closure Recipes
    CS 251 Fall 20192019 Principles of of Programming Programming Languages Languages λ Ben Wood Currying and Partial Application and other tasty closure recipes https://cs.wellesley.edu/~cs251/f19/ Currying and Partial Application 1 More idioms for closures • Function composition • Currying and partial application • Callbacks (e.g., reactive programming, later) • Functions as data representation (later) Currying and Partial Application 2 Function composition fun compose (f,g) = fn x => f (g x) Closure “remembers” f and g : ('b -> 'c) * ('a -> 'b) -> ('a -> 'c) REPL prints something equivalent ML standard library provides infix operator o fun sqrt_of_abs i = Math.sqrt(Real.fromInt(abs i)) fun sqrt_of_abs i = (Math.sqrt o Real.fromInt o abs) i val sqrt_of_abs = Math.sqrt o Real.fromInt o abs Right to left. Currying and Partial Application 3 Pipelines (left-to-right composition) “Pipelines” of functions are common in functional programming. infix |> fun x |> f = f x fun sqrt_of_abs i = i |> abs |> Real.fromInt |> Math.sqrt (F#, Microsoft's ML flavor, defines this by default) Currying and Partial Application 4 Currying • Every ML function takes exactly one argument • Previously encoded n arguments via one n-tuple • Another way: Take one argument and return a function that takes another argument and… – Called “currying” after logician Haskell Curry Currying and Partial Application 6 Example val sorted3 = fn x => fn y => fn z => z >= y andalso y >= x val t1 = ((sorted3 7) 9) 11 • Calling (sorted3 7) returns a closure with: – Code fn y => fn z
    [Show full text]
  • Lecture Notes on First-Class Functions
    Lecture Notes on First-Class Functions 15-411: Compiler Design Rob Simmons and Jan Hoffmann Lecture 25 Nov 29, 2016 1 Introduction In this lecture, we discuss two generalizations of C0: function pointers and nested, anonymous functions (lambdas). As a language feature, nested functions are a nat- ural extension of function pointers. However, because of the necessity of closures in the implementation of nested functions, the necessary implementation strategies are somewhat different. 2 Function pointers The C1 language includes a concept of function pointers, which are obtained from a function with the address-of operator &f. The dynamic semantics can treat &f as a new type of constant, which represents the memory address where the function f is stored. S; η ` (∗e)(e1; e2) B K −! S; η ` e B ((∗_)(e1; e2) ;K) S; η ` &f B ((∗_)(e1; e2);K) −! S; η ` e1 B (f(_; e2) ;K) Again, we only show the special case of evaluation function calls with two and zero arguments. After the second instruction, we continue evaluating the argu- ments to the function left-to-right and then call the function as in our previous dynamics. We do not have to model function pointers using a heap as we did for arrays and pointers since we are not able to change the functions that is stored at a given address. It is relatively straightforward to extend a language with function pointers, be- cause they are addresses. We can obtain that address at runtime by referring to the label as a constant. Any label labl in an assembly file represents an address in memory (since the program must be loaded into memory in order to run), and can LECTURE NOTES NOV 29, 2016 First-Class Functions L25.2 be treated as a constant by writing $labl.
    [Show full text]
  • The Cool Reference Manual∗
    The Cool Reference Manual∗ Contents 1 Introduction 3 2 Getting Started 3 3 Classes 4 3.1 Features . 4 3.2 Inheritance . 5 4 Types 6 4.1 SELF TYPE ........................................... 6 4.2 Type Checking . 7 5 Attributes 8 5.1 Void................................................ 8 6 Methods 8 7 Expressions 9 7.1 Constants . 9 7.2 Identifiers . 9 7.3 Assignment . 9 7.4 Dispatch . 10 7.5 Conditionals . 10 7.6 Loops . 11 7.7 Blocks . 11 7.8 Let . 11 7.9 Case . 12 7.10 New . 12 7.11 Isvoid . 12 7.12 Arithmetic and Comparison Operations . 13 ∗Copyright c 1995-2000 by Alex Aiken. All rights reserved. 1 8 Basic Classes 13 8.1 Object . 13 8.2 IO ................................................. 13 8.3 Int................................................. 14 8.4 String . 14 8.5 Bool . 14 9 Main Class 14 10 Lexical Structure 14 10.1 Integers, Identifiers, and Special Notation . 15 10.2 Strings . 15 10.3 Comments . 15 10.4 Keywords . 15 10.5 White Space . 15 11 Cool Syntax 17 11.1 Precedence . 17 12 Type Rules 17 12.1 Type Environments . 17 12.2 Type Checking Rules . 18 13 Operational Semantics 22 13.1 Environment and the Store . 22 13.2 Syntax for Cool Objects . 24 13.3 Class definitions . 24 13.4 Operational Rules . 25 14 Acknowledgements 30 2 1 Introduction This manual describes the programming language Cool: the Classroom Object-Oriented Language. Cool is a small language that can be implemented with reasonable effort in a one semester course. Still, Cool retains many of the features of modern programming languages including objects, static typing, and automatic memory management.
    [Show full text]