Functional Programming 2.2
Functional Programming 2.2
4.1
Lambda Calculus
formal model of computation
(Church, 1932-33)
Lisp
(McCarthy, 1960) symbolic computations with lists
Scheme, 70s
APL
algebraic programming with arrays
(Iverson, 1962)
let and where clauses
ISWIM
equational reasoning; birth of “pure” functional
(Landin, 1966)
programming ...
ML
(Edinburgh, 1979) originally meta language for theorem proving
Caml 1985, Ocaml
SASL, KRC, Miranda
lazy evaluation
(Turner, 1976-85)
Haskell
“Grand Unification” of functional languages ...
(Hudak, Wadler, et al., 1988)
Functional Programming
◻ Functional programming is a style of programming:
Imperative Programming:
Program = Data + Algorithms
OO Programming:
■ Program = Object. message (object)
Functional Programming:
Program = Functions Functions
2
Functional Programming Languages
◻ Imperative style
int sumto(int n)
{ int i, sum = 0;
for(i = 1; i <= n; i++) sum += i;
return sum;
}
◻ Functional style:
int sumto(int n)
{ if (n <= 0) return 0;
else return sumto(n-1) + n;
}
Why does it matter, anyway?
5
0
Goals
1
What is Functional Programming?
distinguishing features:
2
C# vs. Haskell
3
int sumUpTo(int n) {
int total = 0;
for (int i = n; n > 0; i--)
total += i;
return total;
}
sumUpTo 0 = 0
sumUpTo n = n + sumUpTo (n -1)
Try it!
4
◻ let var1 = 2
◻ let var2 = 3
◻ print(var1 + var2)
◻ //range operator
◻ main :: IO()
◻ main = do print [1..10]
◻ //
Inbuilt Type Class
declaration
❑ add x y = x + y --function definition
numbers is:"
❑ print(add 2 5) --calling a function
Pattern Matching
► The value is compared with each left side until one “fits”
► In sumUpTo, if the value is zero we return zero,
otherwise we fall to the second one
sumUpTo 0 = 0
sumUpTo n = n + sumUpTo (n -1)
Expressions instead of statements
7
–
Why Functional
Programming?
11
To create better software
12
► F# for .NET, Scala and Kotlin for JVM, Swift for iOS
► C# and Java are getting functional constructs
► Functional
► Statically typed
► Pure
► Lazy
Haskell is statically typed
16
20
GH
C
21
Compiler versus interpreter
22
► Compiler (ghc)
► Takes one or more files as an input
► Generates a library or complete executable
► There is no interaction
► How you do things in
Imperatief/Mobiel/Gameprogrammeren
► Interpreter (ghci)
► Interactive, expressions are evaluated on-the-go
► Useful for testing and exploration
► You can also load a file
► Almost as if you have typed in the entire file
► repl.it is web-based ghci
GHC interpreter, ghci
1. Open a command line, terminal or console
► Right now, just repl.it
2. Write ghci and press
◻ GHCi, version 8.0.1: http://www.haskell.org/ghc/
Prelude>
3. Type an expression and press Enter
Prelude> 2 + 3
5
Prelude>
First examples
24
28
Question
Type error!
28
Define a function in a file
30
32
More basic types
33
> 1 == 2 || 3 == 4
◻ False
> 1 < 2 && 3 < 4
◻ True
> nand x y = not (x && y)
ML (META LANGUAGE)
A BRIEF INTRODUCTION
Meta language
◻ From a programming language perspective, a
metalanguage is a language used to make statements
regarding statements made in another language,
known as an object language. Metalanguage helps in
describing the concepts, grammar and objects
associated with a particular programming language.
◻ Metalanguage is widely used in language design,
analysers, compilers and theorem provers. It is also
used in financial systems, bioinformatics and in other
similar applications.
An Overview of ML
◻ ML means "Meta Language." It is a "purely"
functional/applicative language (this is actually a
white lie, but we'll focus primarily on the
functional part).
Application areas:
◻ Education
◻ Systems programming
◻ Important attributes/features that are similar to
those in Scheme/Lisp:Functional programming
style.
◻ Interpreter based.
◻ Heavy use of recursion and higher order functions.
◻ High level data structures well supported (eg.
lists)
◻ Garbage collection
New attributes/features:Statically/Strongly typed.
◻ Type inference
◻ Pattern matching.
◻ Polymorphism
◻ Exception Handling
History
◻ Fig. 1 gives an abbreviated family DAG of the ML family, and a few related
languages. Dotted lines indicate significant omitted nodes. The rounded box
indicates those variants of the ML family that most people would call ML. A
brief history of ML:
◻ 1973: ML invented as part of the University of Edinburgh's LCF project, led by
Robin Milner et al., who were conducting research in constructing automated
theorem provers. Eventually observed that the "Meta Language" they used for
proving theorems was more generally useful as a programming language.
◻ Late 1970's: polymorphic type inference system completed by Milner and
Damas.
◻ Mid-80's: Standard ML; parameterized module system added by Dave
MacQueen; Caml fork at INRIA (France).
◻ 1996: Objective Caml, by Xavier Leroy et al.; adds inheritance to Caml module
system.
◻ 1997: ML97 revision of Standard ML.
Primitive ML data types
◻ numbers
integers (examples: 1, 4, ~3, 0) [Note the ~, not a -.]
reals (examples: 0.0, 3.5, 1.23E~10) [Note the ~.]
◻ booleans (true and false only)
◻ strings (eg. "foo" "bar\n")
◻ Case is significant (true, not TRUE).
Primitive ML operators
◻ Syntax
◻ fun function-name (arg1, arg2, ...) = expression; (* general form *)
◻ - fun addtwo (x) = x+2.0; (* define a simple function *)
◻ > val addtwo = fn : real -> real
◻ Notice that ML deduced the type of the function. How? Why might
ML complain about the following function?
◻ History
ML was created as a metalanguage for the Edinburgh LCF proof assistant in
1973.
It has since developed into its own language, hence the acronymn ML no longer
is a relevant descriptor of the language.
Note - A data type that changes based on its current usage. For example, a programming
language that supports polymorphic typing allows the same routine to work on both integer
and floating point numbers, depending on which values are presented to it.
ML: An Example Program
◻ ML in their words:
“ML has made significant inroads into the computer science
educational and research communities. The exposure of the
type mechanism at the source language level is a feature not
available in other widely used languages. However,
commercial applications of ML programs are few, and so
far it remains mostly a vehicle for computer science
research and educational use.” (That old book).
“…This may be because there are not enough…”
■ Gentle intro to ML: readers comments
Resources
◻ Textbook: Chapter 11
96
◻ Tutorial:
The Scheme Programming Language http://www.scheme.com/tspl3/
(Chapter 1-2)
Yet Another Haskell Tutorial http://www.cs.utah.edu/~hal/htut
(Chapter 1-4, 7)
◻ Implementation:
• DrScheme http://www.drscheme.org/
Lecture 17 – Functional
CSE3302 Programming Languages, UT-Arlington ©Chengkai Li, 2008
Programming, Spring 2008
Scheme: Lisp dialect
◻ Syntax (slightly simplified):
98
Evaluation Rules:
◻ number | string: evaluate to itself
◻ Most expressions use applicative order evaluation (eager evaluation): subexpressions are first
evaluated, then the expression is evaluated.
(correspondingly in imperative language: arguments are evaluated at a call site before they are
passed to the called function.)
Lazy Evaluation: Special Forms
102
◻ if function (if a b c):
a is always evaluated
Either b or c (but not both) is evaluated and returned as result.
c is optional. (if a is false and c is missing, the value of the expression is
undefined.)
e.g., (if (= a 0) 0 (/ 1 a))
◻ cond :
(cond (e1 v1) (e2 v2) ... (else vn))
The (ei vi) are considered in order
ei is evaluated. If it is true, vi is then evaluated, and the value is the result of
the cond expression.
If no ei is evaluated to true, vn is then evaluated, and the value is the result of
the cond expression.
If no ei is evaluated to true, and vn is missing, the value of the expression is
undefined.
(cond ((= a 0) 0) ((= a 1) 1) (else (/ 1 a)))
Lazy Evaluation: Special Forms
103
◻ define function:
declare identifiers for constants and function, and thus put them into symbol
table.
(define (gcd u v)
(if (= v 0) u (gcd v (remainder u v))))
Lazy Evaluation: Special Forms
104
◻ Quote, or ' for short, has as its whole purpose to not evaluate its
argument:
(quote (2 3 4)) or '(2 3 4) returns just (2 3 4).
◻ let function:
create a binding list (a list of name-value assocations), then
evaluate an expression (based on the values of the names)
◻ Is this assignment?
Lists
106
List
Only data structure
Used to construct other data structures.
Thus we must have functions to manipulate lists.
◻ cons: construct a list
(1 2 3) = (cons 1 (cons 2 (cons 3 '())))
(1 2 3) = (cons 1 '(2 3))
◻ car: the first element (head), which is an expression
(car '(1 2 3)) = 1
◻ cdr:the tail, which is a list
(cdr '(1 2 3)) = (2 3)
Data structures
107
◻ (define (append L M)
(if (null? L)
M
(cons (car L) (append (cdr L) M))
)
)
◻ (define (reverse L)
(if (null? L)
M
(append (reverse (cdr L)) (list (car L)))
)
)
Lambda expressions
110
/function values
◻ A function can be created dynamically using a lambda expression, which
returns a value that is a function:
(lambda (x) (* x x))
• higher-order function:
a function that returns a function as its value
or takes a function as a parameter
or both
• E.g.:
• add-x
• compose (next slide)
Higher-order functions
113
(define (compose f g)
(lambda (x) (f (g x))))
(define (map f L)
(if (null? L) L
(cons (f (car L))(map f (cdr L)))))
(define (filter p L)
(cond
((null? L) L)
((p (car L)) (cons (car L)
(filter p (cdr L))))
(else (filter p (cdr L)))))
let expressions as lambdas:
114
◻ A let expression is really just a lambda applied immediately:
(let ((x 2) (y 3)) (+ x y))
is the same as
((lambda (x y) (+ x y)) 2 3)