26
Functional Programming Lecture 1: Introduction Mircea Marin [email protected] February 25, 2020 M. Marin FP: Introduction

Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

  • Upload
    others

  • View
    16

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Functional ProgrammingLecture 1: Introduction

Mircea [email protected]

February 25, 2020

M. Marin FP: Introduction

Page 2: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

IntroductionCourse objectives

Become familiar with the basic notions and principles offunctional programming (FP), and use them to solve concreteproblems.

Description of the paradigm of functional programming.Acquire functional programming skills using the RACKET

programming languageExpected outcome

Ability to discuss issues of functional programming(measured by course tests)Ability to design and implement programs in RACKET thatdemonstrate the concepts covered in the course(measured by problem sets).Design, implement and test short RACKET programs(measured by lab tests and/or mini-projects)

M. Marin FP: Introduction

Page 3: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Organizatorial items

13 lectures, 7 labs (weeks 1,3,5,. . . )Lecturer and TA: Mircea Marin

Grading:Mini-projects &labwork assignments: 50%Colloquium = written exam (week 14): 50%Lab attendance: at least 4 labs

Sources of information (lectures, labworks,)I website: web.info.uvt.ro/~mmarin/lectures/FP/I Recommended bibliography:

H. Abelson, G. J. Sussman, J. Sussman: Structure andInterpretation of Computer Programs. MIT Press, secondedition. 1996.M. Felleisen, R. B. Findler, M. Flatt, S. Krishnamurthi: Howto Design Programs: An Introduction to Programming andComputing. MIT Press. 2001.M. Marin, V. Negru, I. Dramnesc: Principles and Practice ofFunctional Programming. EUVT. 2016.

M. Marin FP: Introduction

Page 4: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

IntroductionWhat is Functional Programming?

In Software Engineering, there are four main programmingparadigms:

1 Imperative (or Procedural) Programming2 Object-oriented Programming (OOP)3 Functional Programming4 Logic Programming

Every programming paradigm has its ownI concepts and notions which are used to guide our way of

thinking and to describe our solutions to problemsI collection of languages with programming constructs for

the main concepts and notionsI model of computation

M. Marin FP: Introduction

Page 5: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Programming paradigms1. Procedural (or imperative) programming

Oldest paradigm: First do this and next do that.

Main notions: command, procedure, and program state.program state: a collection of variables with values.command = execution of an instruction; it changes theprogram state as a function of time.procedure = name given to a collection of instructionswhich can be called as a single command.program = collection of procedure definitions andinstructions to be executed; similar to descriptions ofeveryday routines, such as food recipes and car repair.computation = stepwise execution of instructions in anorder governed by control structures (blocks, conditionals,loops, . . . )

Representative languages: Fortran, Algol, Pascal, Basic, CM. Marin FP: Introduction

Page 6: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

1. Imperative programmingExample of an imperative program (pseudocode)

Compute the value of the smallest element from a list L with nelements:

program state: variables L, r , i ,nbasic instruction: assignment (e.g., m← a)I assignments change the program state

control structures: while, if, . . .procedures: minList, min

M. Marin FP: Introduction

Page 7: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Programming paradigms2. Object-oriented programming (OOP)

world = collection of objects that communicate by sendingmessages to each other.object: description of a concept or notion with

data fields = the state of the objectmethods = operations that can act on the fields of the object

Thus, OOP = generalisation of imperative programming,where the program state is distributed over many objects.message passing = applying a method on an object⇒ theobject state may change.

Usually, the structure of an object (=data fields + methods) isdescribed by a class⇒ object is an instance of a class.⇒ program = collection of class definitions.

classes are organised in inheritance hierarchiesRepresentative languages: Simula, Java, C++, SmallTalk,JavaScript

M. Marin FP: Introduction

Page 8: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Programming paradigms3. Logic Programming (LP)

Answer a question by searching the answer according to afixed, predictable strategy.

Main notions: fact, rule, query.Way of thinking which is useful for solving problems relatedto the extraction of knowledge from basic facts andrelations.

The programmer must describe what he knows as facts andrules collected in a program.The compiler (or interpreter) of the programming languagefinds the answers to all questions we may ask afterwards,using a built-in search strategy.

Representative language: Prologsearch strategy of Prolog: SLDNF-resolution

M. Marin FP: Introduction

Page 9: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

3. Logic programming (LP)Typical example: find the minimum element of a list

Fact: The minimum element of a singleton list made ofnumber m is m.Rules of inference:

1 The minimum of x and y is x if x ≤ y .2 The minimum of x and y is y if y < x .3 The minimum element of a list starting with x , y followed by

sublist t is m if m is the minimum of x and n, where n is theminimum element of the list with first element y followed bysublist t .

Corresponding Prolog program

min(X,Y,X) :- X =< Y.min(X,Y,Y) :- Y < X.minList([M],M).minList([X,Y|T],M) :- minList([Y|T],N), min(X,N,M).

M. Marin FP: Introduction

Page 10: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Programming paradigms4. Functional Programming (FP)

Describe every computation as a request to evaluate anexpression, and use the resulting value for something.

Main notions: function, value, expression.program: collection of function definitions in themathematical sense

The value of a function call depends only on the values ofthe function arguments.

expression = (typically) a combination of nested functioncalls.computation = evaluation of an expression⇒ a value.value = element of a datatype (string, integer, list, etc.) thatcan be

namedstored in a composite data (e.g., element of a list or vector)passed as argument to a function callreturned as result of a function call

M. Marin FP: Introduction

Page 11: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

4. Functional ProgrammingCharacteristic features

Variables are just names given to valuesThere is no assignment⇒ we can not change the valueof a variable⇒ we can not define repetitive computations by iteration.⇒ we define repetitive computations by recursion

Functions are values⇒ we can havefunctions that take function argumentsfunctions that return functions as resultslists of functions, etc.

M. Marin FP: Introduction

Page 12: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Example 1: Computation of n! by recursion

We can not define fact by iteration

fact(int n)i=1; fact:=1;if(i<n)i:=i+1;fact:=fact*i;

endifreturn fact

because there is no assignment in functional programming.But we can define fact by recursion:

fact(int n)if (n==1)

1else

n*fact(n-1)

M. Marin FP: Introduction

Page 13: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Example 2: A function with a function argument

map(f ,L) takes as inputs a function f : A→ B and a list

L = (a1,a2, . . . ,an) of elements from A

and returns the list

(f (a1), f (a2), . . . , f (an)) of elements from B

Assume thatempty(L) recognises if L is empty list

first(L) returns the first element of a list

rest(L) returns the list produced by removing the first elementof L

prepend(e,L) adds element e in front of list L

map(f,L)if (empty(L)) Lelse prepend(f(first(L)),map(f,rest(L)))

M. Marin FP: Introduction

Page 14: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Why learn functional programming?

It has a very simple model of computation:Programs consist (mainly) of function definitionsComputation=evaluation of (nested) function calls

We can define higher-order functions (functions that takefunctions as arguments and/or return functions as results)

⇒ we can write highly modular and reusable code[Hughes:1989]

According to [Thompson:1999]:“Functional languages provide a framework in which thecrucial ideas of modern programming are presented in theclearest possible way. This accounts for their widespreaduse in teaching computing science and also for theirinfluence on the design of other languages.”

M. Marin FP: Introduction

Page 15: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

What will you learn?

How to use DrRacket to write and run functional programsI DrRacket is an integrated development environment (IDE)

for Racket, the current dialect of SchemeI DrRacket is freely available to be installed on Windows,

Linux, MacOS, etc.https://racket-lang.org

When started, DrRacket shows a window with two panels:1 the definitions area, where you can start typing your own

programs, save them for later use and run them.2 the interactions area, where you can interact directly with

the interpreter of RACKET.

M. Marin FP: Introduction

Page 16: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Functional programming languagesEarly history

The first high-level programming language was Fortran(1957). Fortran is an imperative programming language.The second high-level programming language was Lisp(1958).

Designed by people interested in AI ("the science andengineering of making intelligent machines");Lisp became the favoured language for AI researchLisp is acronym for "List Processing": Lists are used torepresent both source code and composite data.

Initial Lisp had no standard specification⇒ many dialectsof Lisp appeared⇒ people were confused, and wanted astandardised and reliable version of Lisp⇒ Common Lisp (ANSI 1994 standard): extensive libraries,

ideal for writing commercial software⇒ Scheme (IEEE 1990 standard): wonderful for educational

purposes.The most recent dialect of Scheme is RACKET.

M. Marin FP: Introduction

Page 17: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Lisp and its dialectsCharacteristic features

They are strict programming languagesI A language is strict if the evaluation of function calls

proceeds as follows: First, we compute the values of thearguments, and next we call the function with the computedvalues.

Example

4+ ((2− 2) ∗ (4− 3)) is the infix notation for the nested functioncall +(4, ∗(0,−(4,3))). The strict evaluation of this expressionis:

+(4, ∗(−(2,2),−(4,3)))→ +(4, ∗(0,−(4,3)))→ +(4, ∗(0,1))→ +(4,0)→ 4

All expressions are written in a peculiar syntax, called theparenthesised prefix notation (see next slide)

M. Marin FP: Introduction

Page 18: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

The parenthesised prefix notation

Every function call f (e1,e2, . . . ,en) is written as(f pe1 pe2 . . . pen)

where pe1,pe2, . . . ,pen are the parenthesised prefixnotations of e1,e2, . . . ,en

Every other composite programming construct is of theform(form-id ...)

where form-id is the identifier of the programmingconstruct.

Characteristics of the parenthesised prefix notationEvery open parenthesis has a corresponding closeperenthesisInstead of comma, we type whitespace (one or moreblanks, newlines, tabs, etc.)

M. Marin FP: Introduction

Page 19: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

The parenthesised prefix notationExamples

((2+7)/3-1)*(7-4) is written as(* (- (/ (+ 2 7) 3) 1) (- 7 4))

The parenthesised prefix notation ofif (n=1) 1 else n*fact(n-1)

is(if (= n 1) 1 (* n (fact (- n 1))))

RemarkThe parenthesised prefix notation of

if cond expr1 else expr2

is (if cond-pe expr1-pe expr2-pe)where cond-pe expr1-pe expr2-pe are the parenthesised prefixnotations of cond, expr1, expr2.

M. Marin FP: Introduction

Page 20: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

RacketValues and built-in datatypes

Values are the simplest expressions: they evaluate tothemselfA value is either atomic or composite.Every value belongs to a datatype.

Datatypes with atomic values:integer: 1 -703 12345678999999floating-point: 1.23 3.14e+87string: "abc"symbol: ’abc(symbol values are preceded by the quote character’)boolean: #t (for truth) #f (for falsehood). . .

Some datatypes have composite values: pairs, lists,vectors, hash tables, etc.

A composite value is a collection of other values.Composite values and datatypes will be described inLecture 2.

M. Marin FP: Introduction

Page 21: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Interacting with DrRacketThe Read-Eval-Print loop (REPL)

In the interactions area, at the input prompt >Type in an expression e in parenthesised prefix notation,and press Entere will be read, evaluated, and the resulted value will beprinted on the next line in the interactions area.

M. Marin FP: Introduction

Page 22: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Interacting with DrRacketThe Read-Eval-Print loop (REPL): Example

Example

the nesting of parentheses clarifies the order in which thefunction applications should be performedthe semicolon ; starts a comment (highlighted with brown)that extends to the end of the line

comments are ignored by the interpreter

M. Marin FP: Introduction

Page 23: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Expressions and definitions

The interpreter of RACKET recognises two kinds of input forms:Expressions: An expression expr is read, evaluated, and its

value is printed in the interactions area.Definitions: A definition is of the form

(define var expr)Definitions are interpreted as follows:

expr is evaluated, and its value is assigned tovariable var .Afterwards, var can be used to refer to thevalue of expr .

Example (Compute√

x2 + y2 for x = 2 and y = 3)> (define x 2)> (define y 3)> (sqrt (+ (* x x) (* y y)))3.605551275463989

M. Marin FP: Introduction

Page 24: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Function definitions

The meaning of an expression

(lambda (x1 . . . xn) body)

is “the function which, for the values of arguments x1, . . . , xn,computes the value of body .”

The evaluation of this expression creates a function, whichis a value that can be assigned to a variable.

Example (the factorial function)> (define fact

(lambda (n)(if (or (= n 0) (= n 1))

1(* n (fact (- n 1))))))

> (fact 5) ; compute 5!120

M. Marin FP: Introduction

Page 25: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

Summary

At the end of this lecture+related lab, you should be know:What are the main programming paradigms of softwareengineeringWhat are the main features of each programming paradigmThe parenthesised prefix notation

write simple arithmetic and logic expressions in theparenthesised prefix notationwrite simple functions, using the lambda-constructUse DrRacket to compute the values of arithmeticexpressions, define functions, and call them.

M. Marin FP: Introduction

Page 26: Functional Programming - Lecture 1: Introductionmircea.marin/lectures/FP/L-01.pdf · Functional programming languages Early history The first high-level programming language was

References

[Hughes:1989] John Hughes. Why functional programmingmatters. Computer Journal, 32(2), 1989.[Thompson:1999] Simon Thompson. The Craft ofFunctional Programming, Second Edition. InternationalComputer Science Series. Pearson Addison Wesley, 1999.

M. Marin FP: Introduction