# Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP)

Size: px
Start display at page:

Download "Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP)"

Transcription

1 Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP) Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology Hong Kong, China Fall 2007

2 Part I Introduction

3 Models of Computation In the 1930 s, long before digital computers were invented, logicians studied abstract concepts of computation. Two simple models of computation: 1 Alan Turing s Turing machines based on an updatable store (memory). 2 Alonzo Church s lambda calculus based on the mathematical concept of functions. The Turing machine idea has great influence on the design of von Neumann computer architecture used by most of today s common CPUs, and imperative programming languages are designed to compute efficiently on the architecture. Lambda calculus is the foundation of functional programming paradigm.

4 von Neumann Computer Architecture Memory results of operations instructions/data ALU CPU Control Unit I/O devices Church-Turing Thesis Any effective computation can be done in one of the two models.

5 Functional Programming Languages Functions are first-class objects: They may be (1) passed as arguments (2) returned as results (3) stored in variables. (c.f. variables in imperative languages.) Basic mode of computation: construction and application of functions. (c.f. assignments in imperative languages.) Principal control mechanism: recursive function applications. (c.f. for-/while-loops in imperative languages.) Freed from side-effects (for pure FPL). Side-Effects: Operations which permanently change the value of a variable (by assignments) or other observable objects (e.g. by printing outputs). Examples: LISP (LISt Processing), Scheme (a dialect of LISP), ML (Meta Language), Haskell, Miranda, etc.

6 Scheme, a dialect of LISP Scheme supports: Static Scope: All identifier references can be resolved at compile time (unlike LISP, which uses dynamic scoping). Dynamic or Latent Typing: All variables are dynamically or latently typed. Any variable can hold any type (imagine that all variables are of the type Object). There are no explicit type declarations. Many scripting languages take the same approach (e.g., Perl, Python, JavaScript, Tcl, etc.) Proper Tail-Recursion: Scheme (but not LISP) implementations are required to be properly tail-recursive, supporting an unbounded number of active tail calls. Pure and Impure Functional Programming: Scheme/LISP encourage pure functional programming, but impure functional programming using some side-effects can also be done.

7 Scheme, a dialect of LISP (cont d) Scheme supports: List-Oriented Programming: The main data structure in Scheme/LISP is the list, implemented as a cons data structure or cons tree. This versatile data structure can easily be applied in many ways, and is easy to manipulate. Programs as Data: The concrete syntax of Scheme/LISP is almost the abstract syntax. All expressions are in prefix notation and fully parenthesized. A big advantage is that programs look just like cons list data structures, which makes it easy to manipulate programs as if they were just data (so programs can write and execute programs). Interpreted: Traditionally, Scheme/LISP implementations all provide an interpreter (and sometimes also a compiler), making interactive debugging easy. Automatic Garbage Collection: All implementations all provide this feature, which Java inherits.

8 Part II Types and Values

9 8 Basic Types, 2 Composite Types type example common operations boolean #t, #f boolean?, not, and, or integer 2, 0, 87 +, -,, quotient, remainder, modulo rational (/ 4 6) +, -,, /, numerator, denominator real 1.3, real?, +, -,, /, floor complex 3+4i complex?, +, -,, / character #\a, #\space, #\newline char? string hello string?, string-ref, string-set! symbol hello symbol?, eqv?, symbol->string dotted pair (1. yes ) list?, null?, cons, car, cdr list (), (1 yes 2.5) (1. ( yes. (2.5. ()))) vector #(1 yes 2.5) vector?, vector-ref, vector-set!, vector

10 Quoting Syntax: (quote < expression >) < expression > Quoting is needed to treat expressions as data. > (define pi ) > pi A quoted item evaluates to itself. quote prevents eval from being called: > (quote pi) pi An equivalent convenient shorthand is provided using : > pi pi

11 Quoting (cont d) Unquoted, * represents the multiplication function: > (define f *) > (f 2 3) 6 Quoted, * represents the symbol with spelling * : > (define f *) > (f 2 3) ERROR: Wrong type to apply: *

12 List Empty list: () (e 1 e 2... e n ) is an abbreviation for (cons e 1 (cons e 2 (cons... (cons e n ())))) cons is the list constructor <new-list> = (cons <item> <list>) (cons 1 (cons 2 (cons 3 ()))) = (cons 1 (cons 2 (3))) = (cons 1 (2 3)) = (1 2 3) Equality on 2 lists is item-by-item.

13 List Operators cons operator: creates a dotted pair of the two operands car operator: returns the first element of a dotted pair (cons cell) cdr operator: returns the second element of a dotted pair (cons cell) append operator: returns a list consisting of the elements of the first list followed by the elements of the other lists

14 List Examples > (car ( )) 1 > (cdr ( )) (2 3 4) > (cons (car ( )) (cdr ( ))) ( ) > (append (5 6) (cdr ( ))) ( )

15 Composite Type: Vector > (vector 4 true cat) #(4 true cat) > (if (equal? 3 8) "X" (vector "Y" 9.5/0.5 (quotient 5 2))) #("Y" ) > (equal? (vector (modulo 14 3) (not #f)) (vector (+ 1 1) #t)) #t > (vector-ref (vector "for" "your" "info") 1) "your" Ordered n-tuple: #(e 1 e 2... e n ). The n expressions may be of mixed types. 2 n-tuples are equal if their corresponding components are equal.

16 Composite Type: Vector.. (vector-ref myvector k) is the item selection operator. (vector-length myvector) returns n. (vector #(e 1 e 2... e n )) returns a newly constructed vector containing the given elements. (make-vector n fill) returns a newly allocated vector of n elements. If the optional second argument is given, then each element is initialized to fill.

17 Identifiers Most identifiers allowed by other programming languages are also acceptable to Scheme. The precise rules for forming identifiers vary among implementations of Scheme, but in all implementations a sequence of letters, digits, and extended alphabetic characters that begins with a character that cannot begin a number is an identifier. In addition, +, -, and... are identifiers. Here are some examples of identifiers: lambda q list->vector soup + V17a <=? a34ktmns the-word-recursion-has-many-meanings Extended alphabetic characters may be used within identifiers as if they were letters. The following are extended alphabetic characters:! \$ % & * + -. / : < = ^ _ ~

18 Identifiers (cont d) Identifiers have two uses within Scheme programs: Any identifier may be used as a variable or as a syntactic keyword. When an identifier appears as a literal or within a literal, it is being used to denote a symbol.

19 Identifiers: Value Binding Syntax: (define < identifier > < expression >) > (define a_df (+ 3 2)) ; c.f. int a_df = 3+2; in C++ > a_df 5 > (define a a (string-append "Albert" " " "Einstein")) > a a "Albert Einstein" > (define a1b2 2) > a1b2 2 > (define +++\$\$\$ (* 9 3)) ; may hold integral value > +++\$\$\$ 27 > (+ +++\$\$\$ +++\$\$\$) ; Though you don t want to do that 54

20 Part III Scheme Functions

21 Lambda: Constructing Anonymous Functions Syntax: (lambda (<formal parameters>) <body>) An anonymous function is a function without a name. lambda returnes a newly constructed anonymous parameterized function value. <formal parameters> is a sequence of parameter names. <body> is an expression, possibly containing occurrences of the parameter names. Used when only a locally defined function is needed. > (lambda (x) (* x x)) ; constructing anonymous function #<procedure #f (x)> > ((lambda (x) (* x x)) 4) ; applying anonymous function 16

22 Defining Named Functions To define a named function, you simply have to bind some identifier (which will be the function name) to a function value. Parameter passing method: Call-By-Value. > (define square (lambda (x) (* x x))) > square #<procedure square (x)> > (square 4) 16 > (define first (lambda (x y) x)) > (first 3 "man") 3

23 Convenient Syntactic Sugar for Named Functions Syntax: (define (<identifier> <formal-parameters>) <body>) > (define (square x) (* x x)) > square #<procedure square (x)> > (square 4) 16 > (define (first x y) x) > (first 3 "man") 3

24 Higher-Order Functions (I) Functions taking functions as arguments: > (define (square x) (* x x)) > (define (twice x) (* 2 x)) > (define (apply5 f) (apply f (5))) > (apply5 square) 25 > (define (apply-to-twice-x f x) (apply f (list (twice x))) > (apply-to-twice-x square 3) 36

25 Higher-Order Functions (II) Functions returning function: > (define (sq_or_twice x) (if (> x 0) square twice)) > (apply (sq_or_twice 2) (5)) 25 > (sq_or_twice 2) #<procedure square (x)>

26 Lambda Calculus Recall this example: > (lambda (x) (* x x)) ; constructing anonymous function #<procedure #f (x)> > ((lambda (x) (* x x)) 4) ; applying anonymous function 16 In the lambda calculus, which was the origin of lambda in LISP/Scheme, the same two lines would be written: (λx. (x x)) (λx. (x x)) 4 We say that applying λx to the expression x x performs a lambda abstraction.

27 Lambda Calculus: Syntactic Conventions (I) A couple conventions for the lambda calculus make it much more readable. First, parentheses may be dropped from (MN) and (λx. M). Notice that function application is an operator; the operator is left associative. E.g., xyz is an abbreviation for ((xy) z). Also, function application has higher precedence than lambda abstraction, so λx. x x is an abbreviation for (λx. (x x))

28 Lambda Calculus: Syntactic Conventions (I..) Quiz: What is the abbreviated syntax for this? ((λx. (x x)) 4) Answer: (λx. x x) 4

29 Lambda Calculus: Syntactic Conventions (II) Second, a sequence of consecutive lambda abstractions, as in λx. λy. λz. M can be written with a single lambda, as in λxyz. M

30 Lambda Calculus: Syntactic Conventions (II..) Quiz: Note that λxyz. M corresponds to what we normally think of as a function with three parameters. If you instead write it as λx. λy. λz. M, then what is the meaning of this: (λx. λy. λz. M) 8 Answer: The value of this expression is a function of two parameters, where y and z remain free variables, but x has already been bound to the value 8. The practice of breaking up multi-parameter functions into single-parameter functions like this in programming is called currying a function (after Tim Curry who promoted this practice, widely found in functional languages like ML and Haskell).

31 Lambda Calculus: Substitution The result of applying an abstraction (λx. M) to an argument N is formalized as substitution of N for x in M, written {N/x} M. Informally, N replaces all free occurrences of x in M. Caution! A fully correct definition of substitution is tricky (there was a long history of not-quite-adequate definitions). This is beyond our scope here. Here is an almost-correct definition: 1 Suppose the free variables of N have no bound occurrences in M. Then the term {N/x} M is formed by replacing all free occurrences of x in M by N. 2 Otherwise, suppose variable y is free in N and bound in M. Consistently replace the binding and corresponding bound occurrences of y in M by some fresh variable z. Repeat the renaming of bound variables in M until case 1 applies, then proceed as in case 1.

32 Lambda Calculus: Substitution examples In the following examples, M has no bound occurrences, so N replaces all occurrences of x in M to form {N/x} M: {u/x} x = u {u/x} (x x) = (u u) {u/x} (x y) = (u y) {u/x} (x u) = (u u) {(λx. x)/x} (x u) = (λx. u)

33 Lambda Calculus: Substitution examples.. In the following examples, M has no free occurrences, so {N/x} M is M itself: {u/x} y = y {u/x} (y z) = (y x) {u/x} (λy. y) = (λy. y) {u/x} (λx. x) = (λx. x) {(λx. x)/x} y = y

34 Lambda Calculus: Substitution examples... In the following examples, free variable u in M has bound occurrences in M, so {N/x} M is formed by first renaming the bound occurrences of u in M: {u/x} (λu. x) = {u/x} (λz. x) = (λz. u) {u/x} (λu. u) = {u/x} (λz. z) = (λz. z)

35 List Function: map The built-in library function map() has 2 or more arguments: a function <func> and one or more lists. It applies function <func> to the elements of the lists as follows. (map <func> <list 1 > <list 2 >...) <func> must be a function taking as many arguments as there are lists and returning a single value. If more than one list is given, then they must all be the same length. Map applies <func> element-wise to the elements of the lists and returns a list of the results, in order. The dynamic order in which <func> is applied to the elements of the lists is unspecified.

36 map: Examples > (define (odd x) (equal? (modulo x 2) 1)) > (map odd (1 2 3)) (#t #f #t) > (map cadr ((a b) (d e) (g h))) (b e h) > (map (lambda (n) (expt n n)) ( )) ( ) > (map + (1 2 3) (4 5 6)) (5 7 9)

37 Part IV Static Scope: let Expression

38 let Expression (let ((<1st-identifier> < E 1 >) (<2nd-identifier> < E 2 >)...) <body-expression>) c.f. Declaration of local variables in C++

39 let Example > (define z (let ((x 3) (y 5)) (+ (* x x) (* 3 y)))) > z 24 As spaces are immaterial, the statement may as well be written all in one single line as follows: > (define z (let ((x 3) (y 5)) (+ (* x x) (* 3 y)))) Quiz: What is the relationship between let and lambda? > (define z ((lambda (x y) (+ (* x x) (* 3 y))) 3 5)) > z 24

40 Nested let Example > (let ((x 3.0) (y 5.0)) (let ((a (+ x y)) (b (- x y))) (let ((f (* a b x)) (g (/ a b y))) (/ f g)))) Quiz: What is the output?

41 Part V Misc: Different Notions of Equality and Equivalence

42 Equality and Equivalence Predicates Scheme (like LISP) offers various notions of equality and equivalence, to support reference vs. value comparisons over different types, with different efficiency tradeoffs. =: Only applies to numeric values. (Very efficient.) char=: Only applies to character values. (Very efficient.) string=: Only applies to string values. eq?: Merely compares references and booleans. (Very efficient; essentially just pointer comparison.) eqv?: Like eq? combined with = plus handles numeric and character values. (Still efficient but slightly less so.) equal?: Recursively compares the contents of pairs, vectors, and strings, applying eqv? on other objects such as numbers and symbols. A rule of thumb is that objects are generally equal? if they print the same. (Least efficient. Why?)

43 eq? vs. eqv? vs. equal? eq? eqv? equal? (eq? () #f) ; cf LISP s nil #f #f #f (eq? a a) #t #t #t (eq? a b) #f #f #f (eq? 2 2) #t only if eqv? #t #t (eq? #\a #\a) #t only if eqv? #t #t (eq? ) unspecified unspecified #t (eq? a a ) #t iff eqv? unspecified #t (eq? #() #()) unspecified unspecified #t (eq? #(1 2) #(1 2)) #t iff eqv? unspecified #t (eq? () ()) #t #t #t (eq? (a) (a)) unspecified unspecified #t (eq? (b) (cdr (a b))) unspecified unspecified #t (eq? (cons 1 2) (cons 1 2)) #f #f #t (let ((x (a))) (eq? x x)) #t #t #t (eq? (lambda () a) (lambda () b)) #f #f #f (eq? (lambda (x) x) (lambda (x) x)) unspecified unspecified unspecified (let ((p (lambda (x) x))) (eq? p p)) #t #t #t

44 Part VI Misc: Value Binding

45 Impure FP: Imperative-style Side-effects (set! <variable> <expression>) <expression> is evaluated, and the resulting value is stored in the location to which <variable> is bound. (set-car! <pair> <expression>) Stores <expression> in the car field of <pair>. (set-cdr! <pair> <expression>) Stores <expression> in the cdr field of <pair>. > (define x (b c)) > (set! x (b c)) > (define y x) > (eq? x y) > (cadr x) #f c > (equal? x y) > (eq? x y) #t #t > (set! y x) > (set! x (d e f)) > (eq? x y) > (cadr x) #t e > (set-cdr! x (g h)) > (eq? x y) > y #f (b g h)

46 Value Binding and Environment The phrase: (define x (b c)) is called a binding; it binds the variable x to a value (b c). Can occur at top-level (global) or at the beginning of a lambda or let body (local). Don t re-define variables; think of them as aliases or constants. You can re-define existing variables at the top-level, for convenience. Whenever an identifier is defined, it s as if a new identifier is created it has nothing whatever to do with any previously existing identifier of the same name. The phrase: (set! x (d e f)) rebinds the variable x to another value (d e f). Don t use set! unless you are intentionally violating pure functional programming. Environment: the current set of ordered pairs (identifier, value) that are visible.

47 Environment: Example (using SML syntax) env: - val x = 17; val x = 17 : int x = 17 - val y = x; val y = 17 : int y = 17 x = 17 - val x = true; val x = true : bool x = true y = 17 - val z = x; x = 17 val z = true : bool z = true x = true y = 17 x = 17

48 Alias and Side Effects Alias: When a data object is visible through more than one name in a single referencing environment, each name is termed an alias. Examples: passed parameters by reference in a function, several pointers to the same object. Pitfall: programs are harder to understand. Side Effects: An operation has side effects if it makes changes which persist after it returns. Examples : A function changes its parameters or modifies global variables (through assignments); printouts. Pitfall : programs are harder to understand, evaluation order of expressions becomes important.

49 Alias and Side Effects: Example int x = 2, y = 5; int Bad(int m) { return x+=m; } void Swap(int a, int b) { int temp = a; a = b; b = temp; x = 4; } int main() { int z = &x; int k = x Bad(7) + x; } printf("k = %d\n", k); Swap(&x, &y); printf("(x,y) = (%d,%d)\n", x, y);

50 Part VII Summary

51 Summary A task is achieved through applications of functions. No pointers! No coercion! No side-effects! Assignment is replaced by value binding. Implicit type inference. Implicit memory management: Objects are allocated as needed, and deallocated when they become inaccessible. Pattern matching program by examples. Allow recursive definition of polymorphic datatypes. Simple exception handling.

52 Summary: FP vs. IP IP: Since IP languages are based on the von Neumann architecture, programmers must deal with the management of variables, assignment of values to them, memory locations, and sometimes even memory allocations. Adv: efficient computation Disadv: laborious construction of programs FP: Do not manipulate memory directly; no variables, no assignments. Instead they work on values that are independent of an underlying machine. Adv: compact language, simple syntax, higher level of programming Disadv: efficiency is sacrificed

53 Summary: FP vs. IP.. IP: FP: IP: FP: IP: FP: Due to aliases and side effects, the effects of a subprogram or a block cannot be determined in isolation from the entire program. Since they only manipulate values, there are no aliases nor side effects. Explicit memory management. Storage is allocated as necessary; and storage that becomes inaccessible is automatically deallocated and reclaimed during garbage collection. The power comes from mimicking operations on the underlying computer architecture with assignments, loops, and jumps. The power comes from recursion and treating functions as first-class values.

### Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP)

Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP) Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology

### Functional Languages. Hwansoo Han

Functional Languages Hwansoo Han Historical Origins Imperative and functional models Alan Turing, Alonzo Church, Stephen Kleene, Emil Post, etc. ~1930s Different formalizations of the notion of an algorithm

### COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

### Functional Programming

Functional Programming CS331 Chapter 14 Functional Programming Original functional language is LISP LISt Processing The list is the fundamental data structure Developed by John McCarthy in the 60 s Used

### Organization of Programming Languages CS3200/5200N. Lecture 11

Organization of Programming Languages CS3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Functional vs. Imperative The design of the imperative languages

### Functional Programming. Big Picture. Design of Programming Languages

Functional Programming Big Picture What we ve learned so far: Imperative Programming Languages Variables, binding, scoping, reference environment, etc What s next: Functional Programming Languages Semantics

### Functional Programming. Pure Functional Programming

Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

### Functional Programming Languages (FPL)

Functional Programming Languages (FPL) 1. Definitions... 2 2. Applications... 2 3. Examples... 3 4. FPL Characteristics:... 3 5. Lambda calculus (LC)... 4 6. Functions in FPLs... 7 7. Modern functional

### Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

Scheme Textbook, Sections 13.1 13.3, 13.7 1 Functional Programming Based on mathematical functions Take argument, return value Only function call, no assignment Functions are first-class values E.g., functions

### Chapter 11 :: Functional Languages

Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Copyright 2016 Elsevier 1 Chapter11_Functional_Languages_4e - Tue November 21, 2017 Historical Origins The imperative

### LECTURE 16. Functional Programming

LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

### SOFTWARE ARCHITECTURE 6. LISP

1 SOFTWARE ARCHITECTURE 6. LISP Tatsuya Hagino hagino@sfc.keio.ac.jp slides URL https://vu5.sfc.keio.ac.jp/sa/ 2 Compiler vs Interpreter Compiler Translate programs into machine languages Compilers are

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

Functional Languages CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Historical Origins 2 The imperative and functional models grew out of work

### Programming Languages

Programming Languages Tevfik Koşar Lecture - XIII March 2 nd, 2006 1 Roadmap Functional Languages Lambda Calculus Intro to Scheme Basics Functions Bindings Equality Testing Searching 2 1 Functional Languages

### 11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT

Functional programming FP Foundations, Scheme (2 In Text: Chapter 15 LISP: John McCarthy 1958 MIT List Processing => Symbolic Manipulation First functional programming language Every version after the

### 4/19/2018. Chapter 11 :: Functional Languages

Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Historical Origins The imperative and functional models grew out of work undertaken by Alan Turing, Alonzo Church, Stephen

### Introduction to Scheme

How do you describe them Introduction to Scheme Gul Agha CS 421 Fall 2006 A language is described by specifying its syntax and semantics Syntax: The rules for writing programs. We will use Context Free

### Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

Scheme Tutorial Introduction Scheme is an imperative language with a functional core. The functional core is based on the lambda calculus. In this chapter only the functional core and some simple I/O is

### Imperative languages

Imperative languages Von Neumann model: store with addressable locations machine code: effect achieved by changing contents of store locations instructions executed in sequence, flow of control altered

### Programming Language Pragmatics

Chapter 10 :: Functional Languages Programming Language Pragmatics Michael L. Scott Historical Origins The imperative and functional models grew out of work undertaken Alan Turing, Alonzo Church, Stephen

### CSC 533: Programming Languages. Spring 2015

CSC 533: Programming Languages Spring 2015 Functional programming LISP & Scheme S-expressions: atoms, lists functional expressions, evaluation, define primitive functions: arithmetic, predicate, symbolic,

### CS 360 Programming Languages Interpreters

CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like

### Principles of Programming Languages COMP3031: Functional Programming in SML

Principles of Programming Languages COMP3031: Functional Programming in SML Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology Hong Kong, China

### Functional programming in LISP

Programming Languages Week 4 Functional programming in LISP College of Information Science and Engineering Ritsumeikan University review of part 3 enumeration of dictionaries you receive a sequence of

### Polymorphic lambda calculus Princ. of Progr. Languages (and Extended ) The University of Birmingham. c Uday Reddy

06-02552 Princ. of Progr. Languages (and Extended ) The University of Birmingham Spring Semester 2016-17 School of Computer Science c Uday Reddy2016-17 Handout 6: Polymorphic Type Systems 1. Polymorphic

### CPS 506 Comparative Programming Languages. Programming Language Paradigm

CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming

### Programming Languages Third Edition. Chapter 7 Basic Semantics

Programming Languages Third Edition Chapter 7 Basic Semantics Objectives Understand attributes, binding, and semantic functions Understand declarations, blocks, and scope Learn how to construct a symbol

### CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages Lecture 15: Review and Functional Programming Zheng (Eddy) Zhang Rutgers University March 19, 2018 Class Information Midterm exam forum open in Sakai. HW4 and

### Programming Systems in Artificial Intelligence Functional Programming

Click to add Text Programming Systems in Artificial Intelligence Functional Programming Siegfried Nijssen 8/03/16 Discover thediscover world at the Leiden world University at Leiden University Overview

### Functional Programming. Pure Functional Languages

Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

### Lambda Calculus see notes on Lambda Calculus

Lambda Calculus see notes on Lambda Calculus Shakil M. Khan adapted from Gunnar Gotshalks recap so far: Lisp data structures basic Lisp programming bound/free variables, scope of variables Lisp symbols,

### CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages Lecture 16: Functional Programming Zheng (Eddy Zhang Rutgers University April 2, 2018 Review: Computation Paradigms Functional: Composition of operations on data.

### Functional Programming Languages (FPL)

Functional Programming Languages (FPL) 1. Definitions... 3 2. Applications... 3 3. Examples... 4 4. FPL Characteristics:... 5 5. Lambda calculus (LC)... 6 5.1. LC expressions forms... 6 5.2. Semantic of

### Functional Programming Lecture 1: Introduction

Functional Programming Lecture 1: Introduction Viliam Lisý Artificial Intelligence Center Department of Computer Science FEE, Czech Technical University in Prague viliam.lisy@fel.cvut.cz Acknowledgements

### Functional Programming. Pure Functional Languages

Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

### FP Foundations, Scheme

FP Foundations, Scheme In Text: Chapter 15 1 Functional Programming -- Prelude We have been discussing imperative languages C/C++, Java, Fortran, Pascal etc. are imperative languages Imperative languages

### CSCI-GA Scripting Languages

CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation

### Lambda Calculus. Variables and Functions. cs3723 1

Lambda Calculus Variables and Functions cs3723 1 Lambda Calculus Mathematical system for functions Computation with functions Captures essence of variable binding Function parameters and substitution Can

### CS 242. Fundamentals. Reading: See last slide

CS 242 Fundamentals Reading: See last slide Syntax and Semantics of Programs Syntax The symbols used to write a program Semantics The actions that occur when a program is executed Programming language

### An Introduction to Scheme

An Introduction to Scheme Stéphane Ducasse stephane.ducasse@inria.fr http://stephane.ducasse.free.fr/ Stéphane Ducasse 1 Scheme Minimal Statically scoped Functional Imperative Stack manipulation Specification

Functional Programming and Haskell Tim Dawborn University of Sydney, Australia School of Information Technologies Tim Dawborn Functional Programming and Haskell 1/22 What are Programming Paradigms? A programming

### Principles of Programming Languages

Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Lesson 6 - Defining a Programming Language Bottom Up Collaboration and Management - Elements of Programming Dana Fisman 1 What we accomplished

### Types and Type Inference

CS 242 2012 Types and Type Inference Notes modified from John Mitchell and Kathleen Fisher Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on Web!! Outline General discussion of

### Lecture #24: Programming Languages and Programs

Lecture #24: Programming Languages and Programs A programming language is a notation for describing computations or processes. These range from low-level notations, such as machine language or simple hardware

### Chapter 15. Functional Programming Languages

Chapter 15 Functional Programming Languages Chapter 15 Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming Language: Lisp Introduction

### A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

A First Look at ML Chapter Five Modern Programming Languages, 2nd ed. 1 ML Meta Language One of the more popular functional languages (which, admittedly, isn t saying much) Edinburgh, 1974, Robin Milner

### Scheme Quick Reference

Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries

### G Programming Languages - Fall 2012

G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

### COMP80 Lambda Calculus Programming Languages Slides Courtesy of Prof. Sam Guyer Tufts University Computer Science History Big ideas Examples:

COMP80 Programming Languages Slides Courtesy of Prof. Sam Guyer Lambda Calculus Formal system with three parts Notation for functions Proof system for equations Calculation rules called reduction Idea:

### Programming Languages

Programming Languages Lambda Calculus and Scheme CSCI-GA.2110-003 Fall 2011 λ-calculus invented by Alonzo Church in 1932 as a model of computation basis for functional languages (e.g., Lisp, Scheme, ML,

### CMSC330. Objects, Functional Programming, and lambda calculus

CMSC330 Objects, Functional Programming, and lambda calculus 1 OOP vs. FP Object-oriented programming (OOP) Computation as interactions between objects Objects encapsulate mutable data (state) Accessed

### CSE 3302 Programming Languages Lecture 8: Functional Programming

CSE 3302 Programming Languages Lecture 8: Functional Programming (based on the slides by Tim Sheard) Leonidas Fegaras University of Texas at Arlington CSE 3302 L8 Spring 2011 1 Functional Programming Languages

### Introduction to Lambda Calculus. Lecture 7 CS /08/09

Introduction to Lambda Calculus Lecture 7 CS 565 02/08/09 Lambda Calculus So far, we ve explored some simple but non-interesting languages language of arithmetic expressions IMP (arithmetic + while loops)

### Functional Programming

Functional Programming COMS W4115 Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science Original version by Prof. Simon Parsons Functional vs. Imperative Imperative programming

### A Small Interpreted Language

A Small Interpreted Language What would you need to build a small computing language based on mathematical principles? The language should be simple, Turing equivalent (i.e.: it can compute anything that

### 11/6/17. Outline. FP Foundations, Scheme. Imperative Languages. Functional Programming. Mathematical Foundations. Mathematical Foundations

Outline FP Foundations, Scheme In Text: Chapter 15 Mathematical foundations Functional programming λ-calculus LISP Scheme 2 Imperative Languages We have been discussing imperative languages C/C++, Java,

### Programming Languages, Summary CSC419; Odelia Schwartz

Programming Languages, Summary CSC419; Odelia Schwartz Chapter 1 Topics Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation Criteria Influences on Language Design

### CMSC 330: Organization of Programming Languages. Lambda Calculus

CMSC 330: Organization of Programming Languages Lambda Calculus 1 Turing Completeness Turing machines are the most powerful description of computation possible They define the Turing-computable functions

### Documentation for LISP in BASIC

Documentation for LISP in BASIC The software and the documentation are both Copyright 2008 Arthur Nunes-Harwitt LISP in BASIC is a LISP interpreter for a Scheme-like dialect of LISP, which happens to have

### CMSC 330: Organization of Programming Languages. Lambda Calculus

CMSC 330: Organization of Programming Languages Lambda Calculus 1 100 years ago Albert Einstein proposed special theory of relativity in 1905 In the paper On the Electrodynamics of Moving Bodies 2 Prioritätsstreit,

### Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

### Programming with Math and Logic

.. Programming with Math and Logic an invitation to functional programming Ed Morehouse Wesleyan University The Plan why fp? terms types interfaces The What and Why of Functional Programming Computing

### Scheme Quick Reference

Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete

### n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!

### Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

Processadors de Llenguatge II Functional Paradigm Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra Paradigm Shift Imperative Paradigm State Machine

### Chapter 5. Names, Bindings, and Scopes

Chapter 5 Names, Bindings, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Scope Scope and Lifetime Referencing Environments Named Constants 1-2 Introduction Imperative

### Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

Scheme: Data CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks ggchappell@alaska.edu

### CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages Lambda Calculus CMSC 330 Summer 2017 1 100 years ago Albert Einstein proposed special theory of relativity in 1905 In the paper On the Electrodynamics of

### Types and Type Inference

Types and Type Inference Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on the course homepage Outline General discussion

### CSCC24 Functional Programming Scheme Part 2

CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages

### CMSC 331 Final Exam Section 0201 December 18, 2000

CMSC 331 Final Exam Section 0201 December 18, 2000 Name: Student ID#: You will have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for

### A Brief Introduction to Scheme (II)

A Brief Introduction to Scheme (II) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Lists Scheme II p.1/29 Lists Aggregate data

### Foundations. Yu Zhang. Acknowledgement: modified from Stanford CS242

Spring 2013 Foundations Yu Zhang Acknowledgement: modified from Stanford CS242 https://courseware.stanford.edu/pg/courses/317431/ Course web site: http://staff.ustc.edu.cn/~yuzhang/fpl Reading Concepts

### 1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine. 2. true / false ML can be compiled. 3. true / false FORTRAN can reasonably be considered

### Recap: Functions as first-class values

Recap: Functions as first-class values Arguments, return values, bindings What are the benefits? Parameterized, similar functions (e.g. Testers) Creating, (Returning) Functions Iterator, Accumul, Reuse

### CS 11 Haskell track: lecture 1

CS 11 Haskell track: lecture 1 This week: Introduction/motivation/pep talk Basics of Haskell Prerequisite Knowledge of basic functional programming e.g. Scheme, Ocaml, Erlang CS 1, CS 4 "permission of

### Introduction to the Lambda Calculus. Chris Lomont

Introduction to the Lambda Calculus Chris Lomont 2010 2011 2012 www.lomont.org Leibniz (1646-1716) Create a universal language in which all possible problems can be stated Find a decision method to solve

### MIT Scheme Reference Manual

MIT Scheme Reference Manual Edition 1.95 for Scheme Release 7.6.0 26 November 2001 by Chris Hanson the MIT Scheme Team and a cast of thousands Copyright c 1988-2001 Massachusetts Institute of Technology

### Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.

Lecture 09: Data Abstraction ++ Parsing Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. program text Parser AST Processor Compilers (and some interpreters)

### SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

### Lambda Calculus. Gunnar Gotshalks LC-1

Lambda Calculus LC-1 l- Calculus History Developed by Alonzo Church during 1930 s-40 s One fundamental goal was to describe what can be computed. Full definition of l-calculus is equivalent in power to

### An Explicit Continuation Evaluator for Scheme

Massachusetts Institute of Technology Course Notes 2 6.844, Spring 05: Computability Theory of and with Scheme February 17 Prof. Albert R. Meyer revised March 3, 2005, 1265 minutes An Explicit Continuation

### Scheme as implemented by Racket

Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the

### Type Systems, Type Inference, and Polymorphism

6 Type Systems, Type Inference, and Polymorphism Programming involves a wide range of computational constructs, such as data structures, functions, objects, communication channels, and threads of control.

### Control in Sequential Languages

CS 242 2012 Control in Sequential Languages Reading: Chapter 8, Sections 8.1 8.3 (only) Section 7.3 of The Haskell 98 Report, Exception Handling in the I/O Monad, http://www.haskell.org/onlinelibrary/io-13.html

### CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages Lambda Calculus CMSC 330 1 Programming Language Features Many features exist simply for convenience Multi-argument functions foo ( a, b, c ) Use currying

### Introduction. chapter Functions

chapter 1 Introduction In this chapter we set the stage for the rest of the book. We start by reviewing the notion of a function, then introduce the concept of functional programming, summarise the main

### CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

CSC312 Principles of Programming Languages : Functional Programming Language Overview of Functional Languages They emerged in the 1960 s with Lisp Functional programming mirrors mathematical functions:

### Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont.

CMSC 330: Organization of Programming Languages OCaml 1 Functional Programming Dialects of ML ML (Meta Language) Univ. of Edinburgh,1973 Part of a theorem proving system LCF The Logic of Computable Functions

### Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

### CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions

### Introduction to Lambda Calculus. Lecture 5 CS 565 1/24/08

Introduction to Lambda Calculus Lecture 5 CS 565 1/24/08 Lambda Calculus So far, we ve explored some simple but non-interesting languages language of arithmetic expressions IMP (arithmetic + while loops)

### CSCE 314 Programming Languages

CSCE 314 Programming Languages Haskell 101 Dr. Hyunyoung Lee 1 Contents 1. Historical Background of Haskell 2. Lazy, Pure, and Functional Language 3. Using ghc and ghci 4. Functions 5. Haskell Scripts

### Lambda Calculus and Lambda notation in Lisp II. Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky.

λ Calculus Basis Lambda Calculus and Lambda notation in Lisp II Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky Mathematical theory for anonymous functions» functions that have

### Pure Lambda Calculus. Lecture 17

Pure Lambda Calculus Lecture 17 Lambda Calculus Lambda Calculus (λ-calculus) is a functional notation introduced by Alonzo Church in the early 1930s to formalize the notion of computability. Pure λ-calculus

### Formal Systems and their Applications

Formal Systems and their Applications Dave Clarke (Dave.Clarke@cs.kuleuven.be) Acknowledgment: these slides are based in part on slides from Benjamin Pierce and Frank Piessens 1 Course Overview Introduction

### Chapter 5 Names, Binding, Type Checking and Scopes

Chapter 5 Names, Binding, Type Checking and Scopes Names - We discuss all user-defined names here - Design issues for names: -Maximum length? - Are connector characters allowed? - Are names case sensitive?