Docsity

Introduction to Functional Programming with Types, Lecture notes of Programming Languages

Toggle sidebar
bg1
CS3110s17 Lecture 1:Introduction to
Functional Programming with Types
Robert Constable
1 Lecture Outline
1. Course Themes
2. Course Mechanics
3. Syntax of a small OCaml subset
4. Semantics of the small OCaml subset
5. Summary
2 Course Themes
This course is about the functional programming paradigm and the tasks for
which it is appropriate. To experience the ideas it is critical to know at
least one mainstream functional programming language and use it to solve
interesting problems. That language should have a rich type system, and
we will see why. Basically it is because types provide high value in clearly
and precisely specifying programming tasks and in reasoning about program
correctness.
On the other hand, if we only provide experience in coding and execut-
ing code, students will have an overly narrow understanding of the nature
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19

Partial preview of the text

Download Introduction to Functional Programming with Types and more Lecture notes Programming Languages in PDF only on Docsity!

CS3110s17 Lecture 1:Introduction to

Functional Programming with Types

Robert Constable

1 Lecture Outline

  1. Course Themes
  2. Course Mechanics
  3. Syntax of a small OCaml subset
  4. Semantics of the small OCaml subset
  5. Summary

2 Course Themes

This course is about the functional programming paradigm and the tasks for which it is appropriate. To experience the ideas it is critical to know at least one mainstream functional programming language and use it to solve interesting problems. That language should have a rich type system, and we will see why. Basically it is because types provide high value in clearly and precisely specifying programming tasks and in reasoning about program correctness.

On the other hand, if we only provide experience in coding and execut- ing code, students will have an overly narrow understanding of the nature

of computer science and the role of PL (programming languages) in driving the field forward. One of the most remarkable characteristics of computer science is that it is a fast moving field relevant to nearly every other science from mathematics, physics, chemistry, biology, psychology, sociology and so forth. Why is this the case? What major changes will this generation of students witness? Knowing answers to these questions might help you par- ticipate in the on-going revolution. We will explore ideas that I find exciting and fundamental. For example, computer science is essential in defining the ground truth for all numerical computations. These contributions are the experimental basis of much science and engineering. I don’t expect that this will make sense to any of you right now, but at the end of the course, I hope it is a point you will make to others who don’t see it.

I mention this example of ground truth because it belongs to the themes that define modern computer science. You need to know the technology, but also know some of the major research themes. We will integrate a few of them into this course. I believe this should be part of our upper level CS curriculum.

2.1 The big picture and relevant research themes

For now, Cornell CS has settled on the OCaml programming language. The “ml” in the name identifies it as one of the class of languages derived from a programming language designed and built at Edinburgh University [9]. The initials stood for “metalanguage” because it was the language used to de- fine a Logic of Computable Functions, LCF for short. Some people now call this small meta language Classic ML. We still use ClassicML at Cornell in research. It is a compact simple language. The “o” in OCaml comes from objects. This interest reflects the rise of Java and object oriented languages. The “C” might appear because some of the influential French computer sci- entists who designed OCaml as an extension of ML, liked to smoke or liked the name of a certain brand of cigarette. OCaml has served us for several years, so many Cornell students and faculty know this language well. It also has imperative features, and in principle we could use it in that mode, but the point of this course is to stress the functional language features. At some

The OCaml programming language is known for its relatively clean and simple type system including polymorphic types. Thus types will be a key focus of the course. OCaml types serve as an introduction to the wider role of type theory in computer science, not only in programming but in the subject called formal methods and in computer security. We will cover a small amount of software engineering using the module data type and some distributed programming based on OCaml’s async package.

Type theory is important in formal methods which is an area of computer science concerned with precisely specifying a wide range of computing tasks and proving that programs exactly satisfy specifications. Types are one way to express what we can say about the structure of inputs to a program and exactly what is required of the outputs as functions of the inputs. Logical formulas are also used to make specifications precise. Highly precise logical specifications are widely used in mathematics, science, engineering, and com- merce. We will see something quite remarkable about OCaml, namely that its type system is rich enough to capture many kinds of logical specifications

  • without ever mentioning logic explicitly. We will take advantage of this important feature of OCaml types to avoid teaching logic as a separate topic in the course. I find this to be especially significant as well as fun. We might even start on this topic in this very first lecture.

Each scientific and engineering discipline has preferred styles for writing specifications. For example, the language COBOL was designed for express- ing “business applications.”^1 FORTRAN was designed for numerical mathe- matics.^2 The richer the type system, the more precisely a programming task can be specified ... up to a point.

The language of mathematics is the richest specification language we know for science, engineering, economics and other disciplines. Its notations and logical specifications are highly precise. For many years school mathematics has been grounded in set theory[31].^3 This is a rich yet sparse language that most people interested in programming will have encountered in at least

(^1) Can you guess some of the words corresponding to the letters of the acronym? (^2) Can you guess the acronym in this programming language name? (^3) There is a specific set theory, Zermelo-Fraenkel with Choice (ZFC), that is often taken

as the foundation for almost all of mathematics[14].

one mathematics course. We will conduct a show of hands to calibrate how common this background is.

SHOW OF HANDS

On the other hand, there is no mainstream programming language built around the primitives of set theory, although this has been attempted at NYU. No proof assistant supports the ZFC formalism. I will be asking you why this is true about programming languages and set theory. By the end of the course you will know in detail why. Here is a high level way to think about that question. Set theory was not designed with any computational primitives.^4

2.2 The concrete example approach

The key construct in a functional programming language is a function, no surprise. In OCaml we write functions in this syntax f un x → exp(x) where exp(x) is an expression that computes to a value when a value is supplied for x. Here is a concrete example f un x → (x + x). Functions can be applied to values. A clear example is (f un x → (x + x)) 17. To compute the value of this application of a function to the number 17, we need to know that + is an operation that reduces 17 + 17 to the value 34.

Already this simple example raises questions. Is f un y → (y + y) the same function or is it different? Could the variable y in this function already have a value, as in programs with state, e.g. perhaps we assigned the value 17 to y? Does this question make sense?

What about a function defined this way (f un x → (f un y → (x + y)))? What happens when we apply this to 17? Does OCaml allow us to “assign to the variable y” as in an expression like this? (f un x → (f un y → y := 2; (x + y)))?

(^4) But see SETL [3, 27].

A current popular approach to formal methods uses software systems called proof assistants and tools called model checkers. The major proof as- sistants are based on type theory. I believe that proof assistants will soon be widely used in education and in programming courses like this one. The NSF has recently invested ten million dollars to advance this approach to teaching program correctness. One of products of this work is the on-line book Software Foundations [22]. The Department of Defence (DoD) is in- vesting a great deal more, on the order of hundreds of millions of dollars to guarantee that critical programs are safe from attack or can respond well to attacks. There are other large investments of which the general public is mostly unaware. Microsoft Research is also investing heavily in this area and is producing very interesting software. One tool is called Danvy that Cornell CS might eventually use for teaching formal methods in Java courses. At the hardware level, Intel and its contractors have invested for many years in using proof assistants to verify elements of its hardware.

Recently DARPA achieved a major success using proof assistants to de- sign an “unhackable drone.” You might have seen news coverage of this suc- cess. This is an example of work in the area called Cyber Physical Systems (CPS). These systems include automobiles and aircraft that use software to help “drive and protect” them. This is currently a very “hot area,” and this course will mention one element of this work since some Cornell CS re- searchers have made significant advances in this area and are keen to help us explain them.

The moderately large CS3110 course staff of highly qualified undergrad- uates will be helping me teach, manage, and grade for this course. All of the undergraduates on the staff have taken an offering of the course in the past and did very well. The most senior course staff have all done the job before. The current staff will be listed on the web page once it has stabilized.

3.2 The concrete example approach

The key construct in a functional programming language is a function, no surprise. In OCaml we write functions in this syntax f un x → exp(x) where

exp(x) is an expression that computes to a value when a value is supplied for x. Here is a concrete example f un x → (x + x). Functions can be applied to values. A clear example is (f un x → (x + x)) 17. To compute the value of this application of a function to the number 17, we need to know that + is an operation that reduces 17 + 17 to the value 34.

Already this simple example raises questions. Is f un y → (y + y) the same function or is it different? Could the variable y in this function already have a value, as in programs with state, e.g. perhaps we assigned the value 17 to y? Does this question make sense?

What about a function defined this way (f un x → (f un y → (x + y)))? What happens when we apply this to 17? Does OCaml allow us to “assign to the variable y” as in an expression like this? (f un x → (f un y → y := 2; (x + y)))?

4 Course Mechanics

  • We offer two recitations per week for most weeks. We might cancel a recitation now and then in favor of more office hours.
  • Only one prelim will be given, it will be given in class and the date will soon be listed on the web site.
  • There will be six programming assignments/problem sets. We will not accept late programming assignments and problem sets because of the need to grade them enmasse. We will deal with medical issues as they arise and may create alternative assignments.
  • There will be a final exam.
  • The final grade will depend about 50% on exams and 50% on the programming assignments.
  • Lecture and recitation attendance is not mandatory and will not be monitored, but it is highly advisable to attend and to study the lec- ture notes. We put a significant amount of effort into these notes.

Academic Integrity We remind you of the Cornell academic integrity poli- cies. If you violate them, it is very likely that we will find out (there are many of us, some extremely vigilant), and the consequences will be severe because we do not tolerate cheating at all.

5 Course Content

This course will teach the OCaml programming language and how to program in the functional style. In addition to learning a new programming language, you will learn new ways to understand the programming process better and how to think rigorously about certain features of programming languages. These skills will help you understand computer science better, and they might help you secure a job in the information technology industry where the ideas we teach are highly valued.

OCaml is a member of the ML family of programming languages which includes Standard ML (SML) [19] which we previously used in this course. The family also includes Microsoft’s F#, and the original language in this family, Classic ML [9], a very small compact language from 1979 still used in research projects. We call the original ML [9] Classic ML. It is not widely used, but is still alive in some proof assistants.

Knowing a language in the ML family is an indication that you were exposed to certain modern computer science ideas that have proven very valuable in writing clean reliable programs and in designing software sys- tems. The ML family is also an excellent basis for presenting the topics in data structures and the analysis of algorithms because the semantics of the language can be given in a simple mathematically rigorous way as we will illustrate [11, 16, 10]. This mathematical foundation will allow us to study in some depth the following ideas.

  1. Functions as values (data) that are inputs and outputs of other func- tions, called higher-order functions.
  1. Recursion as the main control construct and induction as the means of proving properties of programs and data types. Indeed, we will see that induction and recursion are two sides of the same concept, an idea connecting proofs and programs in a mathematically strong way [2].
  2. We will study recursive data types and learn that these data types have natural inductive properties. We will examine the concept of co-recursion and look at co-recursive types such as streams and possibly spreads as well (trees that can grow indefinitely, also called co-trees).
  3. The ML family of functional programming languages is especially appropriate for rigorous thinking about computational mathematics. We will illustrate this by developing some aspects of the real numbers, R in OCaml. These will be infinite precision computable real numbers, and they have been used to present in a computational manner most of the calculus you learn in mathematics, science, and engineering [5, 6]. Computable reals provide the ground truth for all numerical computation against which IEEE floating point arithmetic can be checked when applications are life critical.

Two or three topics in this course are “cutting edge” in the sense that they are at the frontier of computing theory and type theory. So you will encounter a few ideas that are not typically seen until graduate school in computer science at other universities. These are topics that are especially interesting to the Cornell faculty in programming languages who are known for work in language based security.

In particular, we will look briefly at how programs can be formally speci- fied in logic and how proof assistants can help programmers prove rigorously that programs meet their specifications. We will mention from time to time a particular French proof assistant from 2004 that is widely used for this purpose, called Coq [4], and its older relative the Nuprl [1, 7] proof assistant built at Cornell in 1982 and active ever since.^7

These and other proof assistants (Agda, HOL, Isabelle HOL) have con- (^7) The Coq research team at INRIA won the 2013 ACM system award for Coq, and a

key member of the team was Chetan Murthy, a Cornell PhD from the Nuprl group, see Wikipedia, ACM Software System Award, 2013.

Course Topics You can see the sweep of the course and how its main topics are approached from the section headings for our lectures and the accompanying recitations in this offering. They are:

  1. Introduction to OCaml functional programming 4 lectures, 4 recita- tions
  2. Data types and structures 6 lectures, 6 recitations
  3. Verification and testing 4 lectures, 3 recitations
  4. Analysis of algorithms and data structures 4 lectures, 4 recitations
  5. Modularity and code libraries 3 lectures, 3 recitations
  6. Concurrency and communication 4 lectures, 4 recitations

These numbers are not exact, but they give an idea of what this course will stress.

These topics account for 25 lectures and there is room for a review lecture and another enrichment lecture. The content is covered in about 24 lectures and 24 recitations.

Special Focus This offering of the course will look at issues in Cyber Phys- ical Systems. One of the new developments arising from the use of proof assistants is that computation is done with computable real numbers. These are infinite precision reals which have clean mathematical properties, mak- ing it possible to reason precisely about the properties of the code. This is something that is very hard to do when using IEEE floating point numbers which do not have clear mathematical properties.

We will use the computable real numbers to solve problems in computa- tional geometry, e.g. finding the convex hull of a set of points in the plane and finding the area of arbitrary simple polygons. We might also cover the problem of finding all intersecting lines in a region of the plane. These algo- rithms will be programmed using infinite precision computable real numbers.

These are the “real thing.” Understanding these numbers will be a significant part of the first half of the course and beyond. We will build up to the reals by using “big nums” for the integers, then defining the rational numbers and finally the real numbers. Learning to compute and reason about these real numbers will be a central focus of several lectures and problems sets.

Lecture Notes and Readings Many of the lecture notes will be from previous offerings of CS3110, however several lectures including this one will be new material and will be posted on the web around the time of the lecture. Some new lecture notes will include the material from previous offerings, perhaps with additions or modifications.

6 OCaml Syntax

The OCaml alphabet The first step in defining any language precisely, including natural languages, programming languages, and formal logics, is to present its syntax. The syntax determines precisely what strings of characters are programs and what strings are data. The first step is to specify the alphabet of symbols used, the “letters of the alphabet of the programming language.” Let ΣOCaml be this alphabet. In this section we use Σ for short. We use exactly 94 symbols (tokens, characters) which are the 52 letters of the English alphabet, 26 lower case and 26 upper case, and 32 special symbols from the standard key board, and ten digits, 0 to 9. These are available on standard key boards.

In words the thirty two special symbols are these: exclamation point (!), at-sign (@), pound sign (]), dollar sign ($), percent sign (asterisk (*), right parenthesis, left parenthesis, underscore, hyphen (-), plus (+), equal (=), right curly bracket, left curly bracket, right brace (]), left brace ([), vertical line (|), colon (:), semicolon (;), quote (”), apostrophe (’), less (¡), greater (¿), comma, period, question mark (?), tilde (∼), backslash, front slash (/), reverse apostrophe (‘).

Latex uses some of these characters to control the type setting, but the names are quite standard. Some have nicknames, such as “squiggle” for tilde.

expression that reduces under the computation rules when applied to a value or given input. Running a program is evaluating an expression. A value is an OCaml expression that is irreducible under the computation rules. We will next look carefully at how to organize the explanation of programs and data. First a word about the scope of this task.

OCaml is a large industrial strength programming language meant to help people do serious work in science, education, business, government and so forth. Like all such languages it is large, complex, and evolving. We aim to study a subset that is good for teaching important ideas in computer science. Thus there are many features of OCaml that we will not cover. On the other hand, we will present a good framework for learning the entire language as it evolves from year to year as all living languages do.

There is no official OCaml subset for education as has been the case in the past with large commercial programming languages, e.g. at the time when PL1 was a widely used language supported by IBM, there was a Cornell subset called PLC that was widely taught in universities and made Cornell well known in programming languages.^8 The PLC work had an influence on Milners thinking about ML, see the references in Edinburgh LCF [9], the first book on ML.

7 OCaml Semantics

A rigorous mathematical method has been developed for precisely defining how programs execute [28, 23, 15, 24]. The concepts are covered in most modern textbooks on programming languages [19, 30, 17, 20, 10]. We will use these ideas to give an account of OCaml semantics. Here is the first key idea of that semantics.

Definition: We divide the OCaml expressions into two classes, the (^8) Many old languages such as COBOL and PL1 are still in use supporting large indus- trial operations. For mysterious reasons certain languages like C tend to become nearly “immortal”. Others like FORTRAN continue to evolve and are immortal in that way. Java, C++, and Lisp might be like that.

canonical expressions and the non-canonical expressions. The canonical ex- pressions are the values of the language. They are defined as expressions which are irreducible under the computation rules. This is a concept that you need to know for exams and discussions. Sometimes we call these val- ues constants. This is common terminology for numerical values of which OCaml has two types, the integers and the floating point numbers which are approximations of the infinitary real numbers of mathematics. It is not a word typically used for all of the constants of OCaml, some of which are functions and types.

Exercise: Give five examples of canonical OCaml expressions and five non-canonical ones not mentioned in this lecture.

7.1 Expressions and values

Simple values as constants The integer constants are 0, 1, -1, 2, -2, .... These are constants in decimal notation. They are canonical values because no computation rules reduce them. There is a limit to their size on either 32 bit machines or 64 bit machines. OCaml supports both sizes. Thus these numbers are not like the mathematical integers whose value is unbounded and which thus form an unbounded type. OCaml does support an implementation of mathematical integers which in Lisp are called “Bignums.”

We may discuss Bignums later, but we will not go into much detail on the limits of OCaml-integers and OCaml-floats. Later in the course we will show how to define infinite precision real numbers and thus model the type of mathematical reals R exactly.

The type bool is simpler having only two canonical values, the two Booleans, true and false; simpler still is the unit type with one value, ().

Structured values – tuples and records Other canonical forms have structure. For example, (1, 2) is the ordered pair of two integers. This is a value, and we call it a constant as well, although unlike the boolean true

denote “the value of the sine function applied to a variable x.”

The programming languages Lisp and Scheme also allow functions as values. Lisp uses the key word lambda instead of f un. So f un x → x + 1 is written (lambda(x)(x + 1)).

As mentioned above one of the other basic syntactic forms of OCaml is the application of a function to an argument. This is written as f a where f is a function expression and a is another expression. The application operator is implicit in this notation whereas in some programming languages we see application written as ap(f ; a) where the operator is explicit.

7.2 Evaluation and reduction rules

The OCaml run time system executes programs that have been compiled into assembly language. This is in a sense the machine semantics of OCaml evaluation, but it is too detailed to serve as a mathematical model of com- putation that we can reason about at a high level. The ML languages have a semantics at a higher level of reduction rules. These rules are used in textbooks such as The Definition of Standard ML [16].

Evaluation is defined using reduction rules. These rules tell us how to take a single step of computation. We use a computation system called small step reduction.

Here is an example of a very simple reduction rule. We first note that there are two primitive canonical functions, fst and snd, that operate on ordered pairs, that is on expressions of the form (e 1 , e2). They are (built-in) primitive operations.

We want a rule format to tell us that f st(a, b) reduces in one step to a and snd(a, b) reduces in one step to b. The rules tell us that we can think of f st as picking out the first element of an ordered pair while snd picks out the second.

Rule-fst f st(a, b) ↓ a Rule-snd snd(a, b) ↓ b.

Here are rules for the Boolean operators.

Rule Boolean-and true && f alse ↓ f alse Rule Boolean-or true || f alse ↓ true

The general rule for the Boolean operators should take arbitrary expres- sions, say exp1 and exp2 and reveal how those values are computed before the principal Boolean operator is computed. To express such rules, we need to state hypotheses about how these expressions are evaluated. Here is the way OCaml performs the reduction.

Rule Boolean-or-1 exp 1 ↓ true ` exp 1 || exp 2 ↓ true

Rule Boolean-or-2 exp 1 ↓ f alse, exp 2 ↓ true ` exp 1 || exp 2 ↓ true

Rule Boolean-or-3 exp 1 ↓ f alse, exp 2 ↓ f alse ` exp 1 || exp 2 ↓ f alse

These Boolean values are used to evaluate conditional expressions. Rule Conditional-true

bexp ↓ true, exp 1 ↓ v 1 ` (if bexp then exp 1 else exp2) ↓ v 1

Exercise: Write the other rule for evaluating the conditional expression.

Here is the rule for evaluating function application.