You are on page 1of 64

Module M03

Partha Pratim
Das

Functional
Principles of Programming Languages
Programming
Functional Design Module M03: Functional Programming
Functional
Programming
Importance of FP
Examples of FPLs
Lisp
Scheme
Partha Pratim Das
ML/SML & Haskell
Python
Department of Computer Science and Engineering
C++
Applications of FPLs
Indian Institute of Technology, Kharagpur
ILs vis-a-vis FPLs
ppd@cse.iitkgp.ac.in
Haskell

Lisp

Scheme

Presented jointly with Srijoni Majumder, January 17 & 19, 2022


Principles of Programming Languages Partha Pratim Das M03.1
Table of Contents

Module M03

Partha Pratim
1 Functional Programming
Das
Functional Design
Functional Functional Programming
Programming
Functional Design Importance of Functional Programming
Functional
Programming
Examples of Functional Programming Languages
Importance of FP Lisp
Examples of FPLs
Scheme
Lisp
Scheme
ML/SML & Haskell
ML/SML & Haskell Python
Python C++
C++
Applications of FPLs Applications of Functional Programming Languages
ILs vis-a-vis FPLs
Imperative vis-a-vis Functional Programming Languages
Haskell

Lisp 2 Haskell
Scheme
3 Lisp
4 Scheme
Principles of Programming Languages Partha Pratim Das M03.2
Functional Programming

Module M03

Partha Pratim
Das

Functional
Programming
Functional Design
Functional
Programming
Importance of FP
Examples of FPLs
Lisp
Scheme
ML/SML & Haskell
Python
C++
Applications of FPLs
ILs vis-a-vis FPLs

Haskell Functional Programming


Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.3


Functions in Mathematics and Programming

Module M03

Partha Pratim • A function, in the mathematical sense, is a set of operations that perform some
Das
computation on the parameter(s) passed, and return a value
Functional
Programming • A function, in a programming language, is a set of code whose purpose is to compute
Functional Design
Functional
based on the parameter(s) and return a value
Programming
Importance of FP • Functions are often used to promote modularity
Examples of FPLs
Lisp ◦ break down program tasks into small, roughly independent pieces
Scheme
ML/SML & Haskell
◦ promotes structured programming in terms of design
Python ◦ aids debugging, coding, and maintenance
C++
Applications of FPLs • However, the function, as we see them in programming languages, does not
ILs vis-a-vis FPLs
necessarily reflect a mathematical function
Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.4


Functions in Mathematics and Programming

Module M03

Partha Pratim • Functions may act more like procedures


Das
◦ a procedure is another unit of modularity
Functional
Programming ◦ the idea behind a procedure is to accomplish one or more related activities
Functional Design
Functional
◦ the activities should make up some logical goal of the program but may not
Programming
necessarily be based on producing a single result
Importance of FP
Examples of FPLs ◦ procedures may return 0 items or multiple items unlike functions
Lisp
Scheme • In languages like C, there are no procedures, so functions must take on multiple roles
ML/SML & Haskell
Python ◦ mathematical types of functions
C++
Applications of FPLs
◦ functions that act as procedures
ILs vis-a-vis FPLs
• Such functions can produce side effects
Haskell

Lisp
◦ mathematical functions do not produce side effects
Scheme

Principles of Programming Languages Partha Pratim Das M03.5


Functional Design

Module M03
• Functions should
Partha Pratim
Das ◦ be concise
Functional
▷ accomplish only a single task or goal (pop in stack should not return the top element)
Programming
Functional Design
◦ return one item
Functional
Programming
▷ in C, we can wrap return multiple values in a structure
Importance of FP ▷ in C++, we can use reference parameters (side effect)
Examples of FPLs
Lisp
◦ have no side effect
Scheme
ML/SML & Haskell
▷ because the assignment operations are done by function calls, the function calls must
Python produce side effects in such circumstances, but in general, the code should not produce
C++
Applications of FPLs
side effects
ILs vis-a-vis FPLs ▷ most C/C++ function do (like printf, sort)
Haskell ◦ use parameter passing for communication
Lisp
▷ rather than global variables
Scheme
◦ exploit recursion when possible
▷ this simplifies the body of a function and requires fewer or no local variables
Principles of Programming Languages Partha Pratim Das M03.6
What is Functional Programming?

Module M03

Partha Pratim • A program in a functional programming language is basically a function call which likely
Das
makes use of other functions
Functional
Programming ◦ The basic building block of such programs is the function
Functional Design
Functional
◦ Functions produce results (based on arguments), but do not change any memory
Programming
state
Importance of FP
Examples of FPLs ◦ In other words, pure functions do not have any side effects
Lisp
Scheme • Everything is an expression, not an assignment
ML/SML & Haskell
Python ◦ In an imperative language, a program is a sequence of assignments
C++
Applications of FPLs
◦ Assignments produce results by changing the memory state
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.7


Functional Programming Paradigm

Module M03

Partha Pratim • The Functional Programming Paradigm is one of the major programming paradigms
Das
◦ FP is a type of declarative programming paradigm
Functional
Programming ▷ C is procedural
Functional Design
Functional
▷ Java is object oriented
Programming
Importance of FP
▷ SQL is declarative, but it is not FP
Examples of FPLs
Lisp
◦ Also known as applicative programming and value-oriented programming
Scheme
ML/SML & Haskell
• Idea: everything is a function
Python
C++
• Based on sound theoretical frameworks (for example, the lambda calculus)
Applications of FPLs
ILs vis-a-vis FPLs
• Examples of FP languages
Haskell ◦ Early FP language: Lisp
Lisp ◦ Important FPs: ML, Haskell, Miranda, Scheme, Logo
Scheme
◦ FPs in other paradigm languages: C++, Python, Java

Principles of Programming Languages Partha Pratim Das M03.8


Functional Programming Languages

Module M03

Partha Pratim • The design of the imperative languages is based directly on the von Neumann
Das
architecture
Functional
Programming ◦ Efficiency is the primary concern, rather than the suitability of the language for
Functional Design
Functional
software development
Programming
Importance of FP
• The design of the functional languages is based on mathematical functions
Examples of FPLs
Lisp
◦ A solid theoretical basis that is also closer to the user, but relatively unconcerned
Scheme with the architecture of the machines on which programs will run
ML/SML & Haskell
Python
C++
Applications of FPLs
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.9


Programming Language Concepts in Functional Programming

Module M03

Partha Pratim • Anonymous Functions (Module 02)


Das
• Curried functions (Module 02)
Functional
Programming • Functional abstraction (Module 02)
Functional Design
Functional
Programming
• Recursion (Module 02)
Importance of FP
Examples of FPLs
• Higher-order functions (Module 02)
Lisp
Scheme
• Lazy evaluation (Module 04)
ML/SML & Haskell
Python • Type inferencing (Module 04, 05, 07)
C++
Applications of FPLs • Functions as First Class Objects (Module 06)
ILs vis-a-vis FPLs

Haskell
• Polymorphism (Module 04, 05)
Lisp • Formal (Denotational) Semantics (Module 08)
Scheme

Principles of Programming Languages Partha Pratim Das M03.10


Characteristics of Pure FPLs

Module M03

Partha Pratim • Pure FP languages tend to


Das
◦ Have no side-effects
Functional
Programming ◦ Have no assignment statements
Functional Design
Functional
◦ Often have no variables!
Programming
◦ Be built on a small, concise framework
Importance of FP
Examples of FPLs ◦ Have a simple, uniform syntax
Lisp
Scheme
◦ Be implemented via interpreters rather than compilers
ML/SML & Haskell ◦ Be mathematically easier to handle
Python
C++ ◦ Pure FPLs have no side effects
Applications of FPLs
ILs vis-a-vis FPLs ▷ Haskell and Miranda are the two most popular examples
Haskell
• Some FPLs try to be more practical and do allow some side effects
Lisp
◦ Lisp and its dialects (like Scheme)
Scheme
◦ ML (Meta Language) and SML (Standard ML)

Principles of Programming Languages Partha Pratim Das M03.11


Importance of Functional Programming

Module M03

Partha Pratim • In their pure form FPLs dispense with the notion of assignment
Das
◦ it is easier to program in them
Functional
Programming ◦ easier to reason about programs written in them
Functional Design
Functional
• FPLs encourage thinking at higher levels of abstraction
Programming
Importance of FP ◦ support modifying and combining existing programs
Examples of FPLs
Lisp
◦ encourage programmers to work in units larger than statements of conventional
Scheme languages: programming in the large
ML/SML & Haskell
Python • FPLs provide a paradigm for parallel computing
C++
Applications of FPLs ◦ absence of assignment (or single assignment)
ILs vis-a-vis FPLs
◦ independence of evaluation order
Haskell
◦ ability to operate on entire data structures
Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.12


Importance of Functional Programming

Module M03

Partha Pratim • FPLs are valuable in developing executable specifications and prototype
Das
implementations
Functional
Programming ◦ Simple underlying semantics
Functional Design
Functional
▷ rigorous mathematical foundations
Programming
Importance of FP
▷ ability to operate on entire data structures
Examples of FPLs ▷ ideal vehicle for capturing specifications
Lisp
Scheme • FPLs are very useful for AI and other applications which require extensive symbol
ML/SML & Haskell
Python manipulation
C++
Applications of FPLs
• Functional Programming is tied to CS theory
ILs vis-a-vis FPLs
◦ provides framework for viewing decidability questions
Haskell
◦ Good introduction to Denotational Semantics (Module 08)
Lisp

Scheme
▷ functional in form

Principles of Programming Languages Partha Pratim Das M03.13


Lisp

Module M03

Partha Pratim • Defined by John McCarthy in 1958 as a language for AI


Das
• Originally, LISP was a typeless language with only two data types: atom and list
Functional
Programming • Lisp’s lists are stored internally as single-linked lists
Functional Design
Functional
Programming
• Lambda notation was used to specify functions
Importance of FP
Examples of FPLs
• Function definitions, function applications, and data all have the same form
Lisp
Scheme
◦ If the list (A B C) is interpreted as data it is a simple list of three atoms, A, B, and
ML/SML & Haskell C but if interpreted as a function application, it means that the function named A is
Python
C++ applied to the two parameters, B and C
Applications of FPLs
ILs vis-a-vis FPLs • Example (early Lisp):
Haskell
(defun fact (n) (cond ((lessp n 2) 1)(T (times n (fact (sub1 n))))))
Lisp

Scheme
• Common Lisp is the ANSI standard Lisp specification

Principles of Programming Languages Partha Pratim Das M03.14


Scheme

Module M03
• In mid 70’s Sussman and Steele (MIT) defined Scheme as a new LISP-like Language
Partha Pratim
Das
• Goal was to move Lisp back toward it’s simpler roots and incorporate ideas which had
been developed in the PL community since 1960
Functional
Programming ◦ Uses only static scoping
Functional Design
Functional ◦ More uniform in treating functions as first-class objects which can be the values of
Programming
Importance of FP expressions and elements of lists, assigned to variables and passed as parameters
Examples of FPLs
Lisp
◦ Includes the ability to create and manipulate closures and continuations
Scheme
ML/SML & Haskell
▷ A closure is a data structure that holds an expression and an environment of
Python variable bindings in which it is to be evaluated. Closures are used to represent
C++
Applications of FPLs
unevaluated expressions for FPLs with lazy evaluation (Module 04)
ILs vis-a-vis FPLs ▷ A continuation is a data structure which represents the rest of a computation
Haskell
• Example:
Lisp

Scheme (define (fact n) (if (< n 2) 1 (* n (fact (- n 1)))))


• Scheme has mostly been used as a language for teaching Computer programming
concepts where as Common Lisp is widely used as a practical language
Principles of Programming Languages Partha Pratim Das M03.15
ML/SML & Haskell

Module M03 • ML (Meta Language) is a strict, static-scoped functional language with a Pascal-like
Partha Pratim syntax created by Robin Milner et. al. in 1973. Common dialect: Standard ML
Das
• First language to include statically checked polymorphic typing
Functional
Programming
◦ Uses type declarations, but also does type inferencing to determine the types of
Functional Design undeclared variables (Modules 05, 07)
Functional
Programming ◦ Strongly typed (whereas Scheme is essentially typeless) and has no type coercions
Importance of FP
Examples of FPLs • Has exception handling, modules for implementing ADTs, GC and a formal semantics
Lisp
Scheme
• Example: fun cube (x : int) = x * x * x;
ML/SML & Haskell • Haskell is similar to ML (syntax, static scoped, strongly typed, type inferencing)
Python
C++
• Purely functional – no variable, no assignment statement, and no side effect
Applications of FPLs
ILs vis-a-vis FPLs
• Some key features:
Haskell
◦ Uses lazy evaluation (evaluate a subexpression only when needed) (Module 04)
Lisp ◦ Has list comprehensions, which allow it to deal with infinite lists
Scheme
• Example:
fib 0 = 1
fib 1 = 1
fib (n + 2) = fib (n + 1) + fib n
Principles of Programming Languages Partha Pratim Das M03.16
Python

Module M03 • Python supports λ functions: Example:


Partha Pratim ◦ one-line mini-functions >>> def f(x):
Das ◦ can be used anywhere a function is required ... return x*2
Functional • Syntax of λ functions in Pyhton ...
Programming
Functional Design
◦ there is no parenthesis around the argument list >>> f(3)
Functional ◦ no return keyword 6
Programming
Importance of FP
◦ function has no name >>> g = lambda x: x*2
Examples of FPLs
◦ can be called through the variable it is assigned to >>> g(3)
Lisp ◦ can be use without even assigning it to a variable – just an in- 6
Scheme line function >>> (lambda x: x*2)(3)
ML/SML & Haskell
Python • To generalize, a λ function is a function that: 6
C++
◦ takes any number of arguments >>> def f(n):
Applications of FPLs
◦ returns the value of a single expression ...return lambda x: x+n
ILs vis-a-vis FPLs
◦ λ functions cannot contain commands >>> v = f(3)
Haskell
◦ λ functions cannot contain more than one expression >>> v(10)
Lisp
◦ λ functions should be kept simple 13
Scheme
• Functional Programming HOWTO
• Functional Programming In Python
• Functional Programming in Python
• Python and functional programming
Principles of Programming Languages Partha Pratim Das M03.17
C++

Module M03 • C++ supports functional programming through λ’s from C++11 (Module 06)
Partha Pratim
#include <iostream>
Das #include <functional> // Provides template <class Ret, class... Args> class function<Ret(Args...)>;
using namespace std;
Functional
Programming // lambda expressions
Functional Design
auto f = [](int i) { return i + 3; };
Functional
Programming
auto sqr = [](int i) { return i * i; };
Importance of FP auto twice = [](const function<int(int)>& g, int v) { return g(g(v)); };
Examples of FPLs auto comp = [](const function<int(int)>& g, const function<int(int)>& h, int v) { return g(h(v)); };
Lisp
Scheme int main() { auto a = 7, b = 5, c = 3; // Type inferred as int
ML/SML & Haskell cout << f(a) << endl; // 10
Python cout << twice(f, a) << " " << comp(f, f, a) << endl; // 13 13
C++
cout << twice(sqr, b) << " " << comp(sqr, sqr, b) << endl; // 625 625
Applications of FPLs
cout << comp(sqr, f, c) << " " << comp(f, sqr, c) << endl; // 36 12
ILs vis-a-vis FPLs
}
Haskell
• The lambda’s in C++ above correspond to the simply typed λ-expressions below:
Lisp
f ≡ λ(i : Int). i + 3 : Int
Scheme
twice ≡ λ(f : Int → Int). λ(v : Int). f (f v ) : Int
sqr ≡ λ(i : Int). i ∗ i : Int
comp ≡ λ(f : Int → Int). λ(g : Int → Int). λ(v : Int). f (g v ) : Int
Principles of Programming Languages Partha Pratim Das M03.18
Applications of Functional Programming

Module M03

Partha Pratim • Lisp is used for artificial intelligence applications


Das
◦ Knowledge representation
Functional
Programming ◦ Machine learning
Functional Design
Functional
◦ Natural language processing
Programming
◦ Modeling of speech and vision
Importance of FP
Examples of FPLs
Lisp
• Embedded Lisp interpreters add programmability to some systems, such as Emacs
Scheme
ML/SML & Haskell
• Scheme is used to teach introductory programming at many universities
Python
C++
• FPLs are often used where rapid prototyping is desired
Applications of FPLs
ILs vis-a-vis FPLs
• Pure FPLs like Haskell are useful in contexts requiring some degree of program
Haskell verification
Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.19


Imperative vis-a-vis Functional Programming Languages

Module M03
• Imperative Languages • Functional Languages
Partha Pratim
Das ◦ Efficient execution ◦ Inefficient execution
Functional
◦ Complex semantics ◦ Simple semantics
Programming
Functional Design
◦ Complex syntax ◦ Simple syntax
Functional
Programming
◦ Concurrency is programmer ◦ Programs can automatically
Importance of FP designed be made concurrent
Examples of FPLs
Lisp
Scheme
ML/SML & Haskell
Python
C++
Applications of FPLs
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.20


Haskell

Module M03

Partha Pratim
Das

Functional
Programming
Functional Design
Functional
Programming
Importance of FP
Examples of FPLs
Lisp
Scheme
ML/SML & Haskell
Python
C++
Applications of FPLs
ILs vis-a-vis FPLs

Haskell Haskell
Lisp

Scheme Sources:
• Guide to Functional programming (Haskell) - Learn everything

Principles of Programming Languages Partha Pratim Das M03.21


Haskell

Module M03

Partha Pratim
Installations:
Das
sudo add-apt-repository ppa:hvr/ghc
Functional
Programming
sudo apt-get update
Functional Design sudo apt-get install ghc-8.0.2
Functional
Programming or
Importance of FP
Examples of FPLs
sudo apt-get install ghc
Lisp
Scheme
ML/SML & Haskell Type ghci to start the interactive prompt
Python
C++
Applications of FPLs user@ubuntu:~$ ghci
ILs vis-a-vis FPLs

Haskell
GHCi, version 7.10.3: http://www.haskell.org/ghc/ :? for help
Lisp
Prelude>
Scheme To run a haskell program

ghc -o fac fac.hs


Principles of Programming Languages Partha Pratim Das M03.22
Haskell - Basics

Module M03

Partha Pratim
Simple Arithmetics
Das parenthesis rule obeyed
Functional
Programming
75+90
Functional Design 50 * (100 - 4999)
Functional
Programming Negative of numbers
Importance of FP
Examples of FPLs
5 * (-3) not 5 * -3
Lisp
Scheme
Boolean Algebra
ML/SML & Haskell
Python True && False
C++
Applications of FPLs
False || True
ILs vis-a-vis FPLs not (True && True)
Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.23


Haskell - Lists

Module M03

Partha Pratim
In Haskell, lists are a homogenous data structure
Das We can use the let keyword to define a name in ghci
Functional
Programming
Functional Design ghci> let lostNumbers = [4,8,15,16,23,42]
Functional
Programming ghci> lostNumbers
Importance of FP
Examples of FPLs [4,8,15,16,23,42]
Lisp
Scheme
ML/SML & Haskell ghci> [1,2,3,4] ++ [9,10,11,12]
Python
C++
[1,2,3,4,9,10,11,12]
Applications of FPLs
ILs vis-a-vis FPLs

Haskell
ghci> "hello" ++ " " ++ "world"
Lisp "hello world"
Scheme ghci> [’w’,’o’] ++ [’o’,’t’]
"woot"

Principles of Programming Languages Partha Pratim Das M03.24


Haskell - Lists

Module M03

Partha Pratim
Lists comparison
Das
ghci> [3,2,1] > [2,1,0]
Functional
Programming
True
Functional Design ghci> [3,2,1] > [2,10,100]
Functional
Programming True
Importance of FP
Examples of FPLs ghci> [3,4,2] > [3,4]
Lisp
Scheme
True
ML/SML & Haskell ghci> [3,4,2] == [3,4,2]
Python
C++
True
Applications of FPLs
ILs vis-a-vis FPLs

Haskell Nested Lists


Lisp
ghci> let b = [[1,2,3,4],[5,3,3,3],[1,2,2,3,4],[1,2,3]]
Scheme
ghci> b [[1,2,3,4],[5,3,3,3],[1,2,2,3,4],[1,2,3]]
ghci> b ++ [[1,1,1,1]]
[[1,2,3,4],[5,3,3,3],[1,2,2,3,4],[1,2,3],[1,1,1,1]]
Principles of Programming Languages Partha Pratim Das M03.25
Haskell - Lists

Module M03
ghci> head [5,4,3,2,1]
Partha Pratim
Das 5
ghci> tail [5,4,3,2,1]
Functional
Programming [4,3,2,1]
Functional Design
Functional
ghci> last [5,4,3,2,1]
Programming
Importance of FP
1
Examples of FPLs
ghci> init [5,4,3,2,1]
Lisp
Scheme [5,4,3,2]
ML/SML & Haskell
Python
ghci> take 3 [5,4,3,2,1]
C++ [5,4,3]
Applications of FPLs
ILs vis-a-vis FPLs ghci> take 10 (cycle [1,2,3])
Haskell [1,2,3,1,2,3,1,2,3,1]
Lisp -----------------------------------------
Scheme {Texas ranges}
ghci> [’a’..’z’]
"abcdefghijklmnopqrstuvwxyz"
Principles of Programming Languages Partha Pratim Das M03.26
Haskell - Lists

Module M03

Partha Pratim
ghci> [x*2 | x <- [1..10], x*2 >= 12]
Das ghci> [ x | x <- [10..20], x /= 13, x /= 15, x /= 19]
Functional -------------------------------------
Programming
Functional Design
Functional
Programming
Importance of FP Tuples:
Examples of FPLs
Lisp [[1,2],[8,11],[4,5]]. and [[1,2],[8,11,5],[4,5]] both allowed
Scheme
ML/SML & Haskell
but not [(1,2),(8,11,5),(4,5)]
Python ("Christopher", "Walken", 55)
C++
Applications of FPLs ghci> let mhc = ((’a’, 50),(’g’, 40))
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.27


Haskell - Maps and Filters

Module M03

Partha Pratim
map :: (a -> b) -> [a] -> [b]
Das map _ [] = []
Functional map f (x:xs) = f x : map f xs
Programming
Functional Design
-------------------------------
Functional
Programming
ghci> map (+3) [1,5,3,1,6]
Importance of FP [4,8,6,4,9]
Examples of FPLs
Lisp ghci> map (++ "!") ["BIFF", "BANG", "POW"]
Scheme
ML/SML & Haskell
["BIFF!","BANG!","POW!"]
Python ghci> map (replicate 3) [3..6]
C++
Applications of FPLs
[[3,3,3],[4,4,4],[5,5,5],[6,6,6]]
ILs vis-a-vis FPLs
-------------------------------
Haskell
ghci> filter (>3) [1,5,3,2,1,6,4,3,2,1]
Lisp
[5,6,4]
Scheme
ghci> filter (==3) [1,2,3,4,5]
[3]
Principles of Programming Languages Partha Pratim Das M03.28
Haskell - Functions

Module M03

Partha Pratim
In Haskell, functions are called by writing the function name, a space and then the
Das parameters, separated by spaces.
Functional
Programming
Functional Design
Functional
Programming ghci> max 100 101
Importance of FP
Examples of FPLs
ghci> succ 8
Lisp
ghci> (succ 9) + (max 5 4) + 1
Scheme
ML/SML & Haskell
Python
C++
Applications of FPLs ghci> bar (bar 3)?
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.29


Haskell - Functions

Module M03

Partha Pratim doubleMe x = x + x


Das

Functional
Programming
Functional Design Prelude> :l func2
Functional
Programming [1 of 1] Compiling Main ( func2.hs, interpreted )
Importance of FP
Examples of FPLs
Ok, one module loaded.
Lisp *Main> doubleUs x y = doubleMe x + doubleMe y
Scheme
ML/SML & Haskell *Main> doubleUs 4 5
Python
C++
18
Applications of FPLs
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.30


Haskell - Functions

Module M03

Partha Pratim
Das doubleMe x = x + x
Functional
doubleUs x y = x*2 + y*2
Programming doubleSmallNumber x = if x > 100
Functional Design
Functional then x
Programming
Importance of FP
else x*2
Examples of FPLs
Lisp
addThree :: Int -> Int -> Int -> Int
Scheme addThree x y z = x + y + z
ML/SML & Haskell
Python
C++ describeList :: [a] -> String
Applications of FPLs
ILs vis-a-vis FPLs describeList xs = "The list is " ++ case xs of [] -> "empty."
Haskell [x] -> "a singleton list."
Lisp xs -> "a longer list."
Scheme

Principles of Programming Languages Partha Pratim Das M03.31


Haskell - Functions

Module M03

Partha Pratim
Das

Functional
Programming maximum’ :: (Ord a) => [a] -> a
Functional Design
Functional maximum’ [] = error "maximum of empty list"
Programming
Importance of FP
maximum’ [x] = x
Examples of FPLs
Lisp
maximum’ (x:xs) = max x (maximum’ xs)
Scheme
ML/SML & Haskell
Python
C++ main = print (describeList "pp")
Applications of FPLs
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.32


Haskell - Functions

Module M03

Partha Pratim
Different approaches to define a function
Das

Functional
reverse’ :: [a] -> [a]
Programming reverse’ [] = []
Functional Design
Functional reverse’ (x:xs) = reverse xs ++ [x]
Programming
Importance of FP
Examples of FPLs
Lisp
Scheme
ML/SML & Haskell
reverse2 xs = app ([], xs)
Python where
C++
Applications of FPLs app (ys, []) = ys
ILs vis-a-vis FPLs
app (ys, (x:xs)) = app ((x:ys), xs)
Haskell

Lisp

Scheme
main = print (reverse2 [1,2,3,4])
main = print (reverse’[1,2,3,4])
[4,3,2,1]
Principles of Programming Languages Partha Pratim Das M03.33
Haskell - lambdas

Module M03 Lambdas are basically anonymous functions that are used because we need some functions
Partha Pratim only once.
Das

Functional numLongChains :: Int


Programming
Functional Design
numLongChains = length (filter (\xs -> length xs > 15)
Functional
Programming
(map chain [1..100]))
Importance of FP ------------------------------------------------
Examples of FPLs
Lisp map (+3) [1,6,3,2] and map (\x -> x + 3) [1,6,3,2] are equivalent
Scheme
ML/SML & Haskell
since both (+3) and (\x -> x + 3) are functions that take a number and
Python add 3 to it.
C++
Applications of FPLs ------------------------------------------------
ILs vis-a-vis FPLs
Like normal functions, lambdas can take any number of parameters:
Haskell
ghci> zipWith (\a b -> (a * 30 + 3) / b) [5,4,3,2,1] [1,2,3,4,5]
Lisp
[153.0,61.5,31.0,15.75,6.6]
Scheme

Principles of Programming Languages Partha Pratim Das M03.34


Python - Lambdas

Module M03

Partha Pratim
Das def muliplyBy (n):
return lambda x: x*n
Functional
Programming double = multiplyBy(2)
Functional Design
Functional
---------------------------------------------------
Programming
Importance of FP
sequences = [10,2,8,7,5,4,3,11,0, 1]
Examples of FPLs
filtered_result = filter (lambda x: x > 4, sequences)
Lisp
Scheme print(list(filtered_result))
ML/SML & Haskell
Python
C++ [10, 8, 7, 5, 11]
Applications of FPLs
ILs vis-a-vis FPLs -----------------------------------------------------
Haskell sequences = [10,2,8,7,5,4,3,11,0, 1]
Lisp filtered_result = map (lambda x: x*x, sequences)
Scheme print(list(filtered_result))

[100, 4, 64, 49, 25, 16, 9, 121, 0, 1]


Principles of Programming Languages Partha Pratim Das M03.35
Haskell - Recursion

Module M03

Partha Pratim
maximum’ :: (Ord a) => [a] -> a
Das maximum’ [] = error "maximum of empty list"
Functional maximum’ [x] = x
Programming
Functional Design
maximum’ (x:xs) = max x (maximum’ xs)
Functional
Programming
Importance of FP replicate’ :: (Num i, Ord i) => i -> a -> [a]
Examples of FPLs
Lisp replicate’ n x
Scheme
ML/SML & Haskell
| n <= 0 = []
Python | otherwise = x:replicate’ (n-1) x
C++
Applications of FPLs
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.36


Haskell - Function Examples

Module M03
Quicksort
Partha Pratim
Das ----------------------------------------
quicksort :: (Ord a) => [a] -> [a]
Functional
Programming quicksort [] = []
Functional Design
Functional
quicksort (pivot:xs) =
Programming
Importance of FP
quicksort [x | x <- xs, x < pivot] ++
Examples of FPLs
[pivot] ++
Lisp
Scheme quicksort [x | x <- xs, x >= pivot]
ML/SML & Haskell
Python
C++ Finding a maximum element in a binary tree
Applications of FPLs
ILs vis-a-vis FPLs -----------------------------------------
Haskell data Tree a = Leaf | Node a (Tree a) (Tree a)
Lisp maxElement :: (Ord a) => Tree a -> Maybe a
Scheme maxElement Leaf = Nothing
maxElement (Node v l r) = maximum [Just v, maxElement l, maxElement r]

Principles of Programming Languages Partha Pratim Das M03.37


Haskell - Types and Classes

Module M03
ghci> :t ’a’
Partha Pratim
Das ’a’ :: Char
ghci> :t True
Functional
Programming True :: Bool
Functional Design
Functional
ghci> :t "HELLO!"
Programming
Importance of FP
"HELLO!" :: [Char]
Examples of FPLs
ghci> :t (True, ’a’)
Lisp
Scheme (True, ’a’) :: (Bool, Char)
ML/SML & Haskell
Python
ghci> :t 4 == 5
C++ 4 == 5 :: Bool
Applications of FPLs
ILs vis-a-vis FPLs

Haskell Types of functions


Lisp addThree :: Int -> Int -> Int -> Int
Scheme addThree x y z = x + y + z
factorial :: Integer -> Integer
factorial n = product [1..n]
Principles of Programming Languages Partha Pratim Das M03.38
Haskell - Statically Typed

Module M03
describeList :: [a] -> String
Partha Pratim
Das describeList xs = "The list is " ++ case xs of [] -> "empty."
[x] -> "a singleton list."
Functional
Programming xs -> "a longer list."
Functional Design
Functional
error if string is 2
Programming
Importance of FP
----------------------------------------------
Examples of FPLs
haskell_programs/func.hs:13:54:
Lisp
Scheme No instance for (Num [Char]) arising from the literal ‘2’
ML/SML & Haskell
Python
In the expression: 2
C++ In a case alternative: xs -> 2
Applications of FPLs
ILs vis-a-vis FPLs In the second argument of ‘(++)’, namely
Haskell ‘case xs of {
Lisp [] -> "empty."
Scheme [x] -> "a singleton list."
xs -> 2 }’
Failed, modules loaded: none.
Principles of Programming Languages Partha Pratim Das M03.39
Python – Strong typing, dynamic typing

Module M03
p = 3
Partha Pratim
Das if p>2:
p = "two"
Functional
Programming print("two")
Functional Design
Functional
else:
Programming
Importance of FP
p = 1
Examples of FPLs
print (p)
Lisp
Scheme
ML/SML & Haskell
Python
---------------------------
C++ p = 3
Applications of FPLs
ILs vis-a-vis FPLs if p>2:
Haskell print("two" + p)
Lisp else:
Scheme print (p)

Principles of Programming Languages Partha Pratim Das M03.40


Haskell - Evaluation Strategies

Module M03

Partha Pratim
{Haskell
Das add x y = x + x
Functional
Programming
Functional Design
#Python
Functional
Programming
def add( x , y ) :
Importance of FP return x + x
Examples of FPLs
Lisp
Scheme
ML/SML & Haskell
Python
C++
Applications of FPLs
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.41


Haskell vs Python

Module M03

Partha Pratim
Lazy Evaluation in Haskell, Eager Evaluation in Python
Das {Haskell
add 4 5
Functional
Programming Result : 8
Functional Design
Functional
add 10 (89/0)
Programming
Importance of FP
Result : 20
Examples of FPLs
Lisp
Scheme #Python
ML/SML & Haskell
Python
print( add(4 , 5) )
C++ Result : 8
Applications of FPLs
ILs vis-a-vis FPLs print( add(10 , (89/0) ) )
Haskell Result : Traceback (most recent call last):
Lisp File \test.py", line 7, in <module>
Scheme print( add(10 , (89/0) ) )
ZeroDivisionError: division by zero

Principles of Programming Languages Partha Pratim Das M03.42


Haskell vs ML

Module M03

Partha Pratim
Eager Evaluation in ML vs Lazy Evaluation in Haskell
Das > (square (square 2)) * (square (square 2))
Functional >((square 2) * (square 2)) * ((square 2) * (square 2))
Programming
Functional Design
> ((2 * 2) * (2 * 2)) * ((2 * 2) * (2 * 2))
Functional
Programming
> (4 * 4) * (4 * 4)
Importance of FP > 16 * 16
Examples of FPLs
Lisp > 256
Scheme
ML/SML & Haskell
Python > (square (square 2)) * (square (square 2))
C++
Applications of FPLs
> ((square 2) * (square 2)) * (square (square 2))
ILs vis-a-vis FPLs > ((2 * 2) * (square 2)) * (square (square 2))
Haskell > (4 * (square 2)) * (square (square 2))
Lisp
> (4 * (2 * 2)) * (square (square 2))
Scheme
> (4 * 4) * (square (square 2))
> 16 * (square (square 2))
> ... > 256
Principles of Programming Languages Partha Pratim Das M03.43
Haskell - Infinite Lists

Module M03

Partha Pratim
take 5 [ 4 .. ] which gives us the first 5 elements of [ 4 .. ]
Das which are [4,5,6,7,8].
Functional
Programming
Functional Design
Functional
Programming
addDigits :: Int -> Int
Importance of FP addDigits n = foldl (\acc char -> acc + digitToInt char^len ) 0 $ show n
Examples of FPLs
Lisp where len = length (show n)
Scheme
ML/SML & Haskell
Python isArmstrong :: Int -> Bool
C++
Applications of FPLs
isArmstrong n = addDigits n == n
ILs vis-a-vis FPLs

Haskell

Lisp
armstrongNumbers :: Int -> [Int]
Scheme
armstrongNumbers n = take n $ filter isArmstrong [100..]

Principles of Programming Languages Partha Pratim Das M03.44


Haskell - Input / Output

Module M03

Partha Pratim
main = putStrLn "hello, world"
Das ghci> :t putStrLn
Functional putStrLn :: String -> IO ()
Programming
Functional Design
ghci> :t putStrLn "hello, world"
Functional
Programming
putStrLn "hello, world" :: IO ()
Importance of FP ------------------------------------------------
Examples of FPLs
Lisp main = do
Scheme
ML/SML & Haskell
putStrLn "Hello, what’s your name?"
Python name <- getLine
C++
Applications of FPLs putStrLn ("Hey " ++ name ++ ", you can login!")
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.45


Lisp

Module M03

Partha Pratim
Das

Functional
Programming
Functional Design
Functional
Programming
Importance of FP
Examples of FPLs
Lisp
Scheme
ML/SML & Haskell
Python
C++
Applications of FPLs
ILs vis-a-vis FPLs

Haskell Lisp
Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.46


Lisp - Basics

Module M03

Partha Pratim
sudo apt-get install sbcl
Das type sbcl
Functional
Programming
Functional Design
Functional
Programming * (+ 3 2)
Importance of FP
Examples of FPLs (setq x 10)
Lisp
Scheme
(print (type-of x))
ML/SML & Haskell (INTEGER 0 4611686018427387903)
Python
C++
Applications of FPLs
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.47


Lisp - Arrays

Module M03
(write (setf my-array (make-array ’(2))))
Partha Pratim
Das (terpri)
(setf (aref my-array 0) 25)
Functional
Programming (setf (aref my-array 1) 23)
Functional Design
Functional
Programming
Importance of FP
(write my-array)
Examples of FPLs
--------------------------------
Lisp
Scheme (setf x (make-array ’(3 3)
ML/SML & Haskell
Python
:initial-contents ’((0 1 2 ) (3 4 5) (6 7 8))))
C++ (write x)
Applications of FPLs
ILs vis-a-vis FPLs --------------------------------
Haskell (setq a (make-array ’(4 3)))
Lisp (dotimes (i 4)
Scheme (dotimes (j 3)
(setf (aref a i j) (list i ’x j ’= (* i j))))
---------------------------------
Principles of Programming Languages Partha Pratim Das M03.48
Lisp - Lists

Module M03

Partha Pratim
Das (write (car ’(a b c d e f)))
Functional (terpri)
Programming
Functional Design
(write (cdr ’(a b c d e f)))
Functional
Programming
(terpri)
Importance of FP (write (cons ’a ’(b c)))
Examples of FPLs
Lisp (terpri)
Scheme
ML/SML & Haskell
(write (list ’a ’(b c) ’(e f)))
Python (terpri)
C++
Applications of FPLs
(write (append ’(b c) ’(e f) ’(p q) ’() ’(g)))
ILs vis-a-vis FPLs
(terpri)
Haskell
(write (last ’(a b c d (e f))))
Lisp
(terpri)
Scheme
(write (reverse ’(a b c d (e f))))

Principles of Programming Languages Partha Pratim Das M03.49


Lisp - Functions and Lambdas

Module M03

Partha Pratim
(defun name (parameter-list)
Das "Optional documentation string."
Functional body)
Programming
Functional Design
------------------------------
Functional
Programming
(defun averagenum (n1 n2 n3 n4)
Importance of FP (/ ( + n1 n2 n3 n4) 4))
Examples of FPLs
Lisp (write(averagenum 10 20 30 40))
Scheme
ML/SML & Haskell
-------------------------------
Python (defun area-circle(rad)
C++
Applications of FPLs "Calculates area of a circle with given radius"
ILs vis-a-vis FPLs
(terpri)
Haskell
(format t "Radius: ~5f" rad)
Lisp
(format t "~%Area: ~10f" (* 3.141592 rad rad)))
Scheme
(area-circle 10)

Principles of Programming Languages Partha Pratim Das M03.50


Lisp - Lambdas and Functions

Module M03 Finding if a list is Palindrome (2 ways)


Partha Pratim ------------------------------
Das
(defun P (list)
Functional
Programming (loop
Functional Design
:for left :on list
Functional
Programming :for right :in (reversed-spine list)
Importance of FP
Examples of FPLs :until (or (eq left right) (eq (cdr left) right))
Lisp
Scheme
:unless (eql (car left) (car right)) :do (return nil)
ML/SML & Haskell :finally (return t)))
Python
C++ (defun P (list)
Applications of FPLs
ILs vis-a-vis FPLs
(loop
Haskell
:with data = (coerce list ’vector)
Lisp :for i :from 0
Scheme :for j :from (1- (length data)) :by -1
:while (< i j)
:always (eql (aref data i) (aref data j))))
Principles of Programming Languages Partha Pratim Das M03.51
Lisp - Lambdas and Functions

Module M03
Finding duplicates in a list
Partha Pratim
Das ------------------------------
Functional
(defun dupli (list)
Programming (mapcan (lambda (item) (list item item)) list))
Functional Design
Functional
Programming
Importance of FP (defun dupli (list)
Examples of FPLs
Lisp
(loop
Scheme :for item :in list
ML/SML & Haskell
Python
:collect item
C++
Applications of FPLs
:collect item))
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.52


Lisp - Lambdas and Functions

Module M03

Partha Pratim
Retrieve a given number of randomly selected elements from a list.
Das ------------------------------
Functional (defun remove-at (list index)
Programming
Functional Design
(cond
Functional
Programming
((< index 1) (error "Invalid index"))
Importance of FP ((= index 1) (rest list))
Examples of FPLs
Lisp (t (cons (first list) (remove-at (rest list) (1- index))))))
Scheme
ML/SML & Haskell
Python (defun rnd-select (list count)
C++
Applications of FPLs (if (zerop count)
ILs vis-a-vis FPLs
’()
Haskell
(let ((i (random (length list))))
Lisp
(cons (elt list i) (rnd-select (remove-at list (1+ i)) (1- count))))))
Scheme

Principles of Programming Languages Partha Pratim Das M03.53


Lisp - Input / Output

Module M03

Partha Pratim
; the function AreaOfCircle
Das ; calculates area of a circle
Functional ; when the radius is input from keyboard
Programming
Functional Design
(defun AreaOfCircle()
Functional
Programming
(terpri)
Importance of FP (princ "Enter Radius: ")
Examples of FPLs
Lisp (setq radius (read))
Scheme
ML/SML & Haskell
(setq area (* 3.1416 radius radius))
Python (princ "Area: ")
C++
Applications of FPLs (write area))
ILs vis-a-vis FPLs
(AreaOfCircle)
Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.54


Scheme

Module M03

Partha Pratim
Das

Functional
Programming
Functional Design
Functional
Programming
Importance of FP
Examples of FPLs
Lisp
Scheme
ML/SML & Haskell
Python
C++
Applications of FPLs
ILs vis-a-vis FPLs

Haskell Scheme
Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.55


Scheme - Basics

Module M03

Partha Pratim
sudo apt-get install mit-scheme
Das type mit-scheme
Functional ----------------
Programming
Functional Design
(+ 3 5)
Functional
Programming
(fac 6)
Importance of FP (append ’(a b c) ’(1 2 3 4))
(- 10 3) → 7
Examples of FPLs
Lisp
Scheme
ML/SML & Haskell
(* 2 3) → 6
Python (/ 29 3) → 29/3
(/ 9 6) → 3/2
C++
Applications of FPLs
ILs vis-a-vis FPLs

Haskell
(quotient 7 3) → 2
(modulo 7 3) → 1
Lisp

Scheme
(sqrt 8) → 2.8284271247461903

Principles of Programming Languages Partha Pratim Das M03.56


Scheme - Lists and Operations

Module M03
(cons ’1 ’(2 3 4))
Partha Pratim
Das car -- returns the first member of a list or dotted pair.
Functional
Programming (car ’(123 245 564 898)) is 123
Functional Design
Functional
(car ’(this (is no) more difficult)) is this
Programming
Importance of FP
Examples of FPLs
cdr -- returns the list without its first item
Lisp
Scheme (cdr ’(it rains every day)) is (rains every day)
ML/SML & Haskell
Python
(cdr (cdr ’(a b c d e f))) is (c d e f)
C++ (car (cdr ’(a b c d e f))) is b
Applications of FPLs
ILs vis-a-vis FPLs

Haskell (length ’(1 3 5 9 11)) is 5


Lisp

Scheme (reverse ’(1 3 5 9 11)) is (11 9 5 3 1)

(append ’(1 3 5) ’(9 11)) is (1 3 5 9 11)


Principles of Programming Languages Partha Pratim Das M03.57
Scheme - Lists and Operations

Module M03

Partha Pratim
(let ((list1 ’(a b c)) (list2 ’(d e f)))
Das (cons (cons (car list1)
Functional (car list2))
Programming
Functional Design
(cons (car (cdr list1))
Functional
Programming
(car (cdr list2)))))
Importance of FP
Examples of FPLs
Lisp (let ([a 4] [b -3])
Scheme
ML/SML & Haskell
(let ([a-squared (* a a)]
Python [b-squared (* b b)])
C++
Applications of FPLs (+ a-squared b-squared)))
ILs vis-a-vis FPLs

Haskell
(let ([x 1])
Lisp
(let ([x (+ x 1)])
Scheme
(+ x x)))

Principles of Programming Languages Partha Pratim Das M03.58


Scheme - Dynamically typed

Module M03

Partha Pratim
Das

Functional
Programming
Functional Design
different return types allowed, due to dynamically typed
Functional
Programming
Importance of FP (if (> 3 2) ’yes ’3)
Examples of FPLs
Lisp
Scheme
ML/SML & Haskell
Python
C++
Applications of FPLs
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.59


Scheme - Lambdas and Functions

Module M03
(define pi 3.14)
Partha Pratim
Das
((lambda (x) (+ x x)) (* 3 4)) - Anonymous
Functional
Programming
Functional Design
Functional
Programming
Importance of FP
(define square (lambda (x) (* x x))) - bindings
Examples of FPLs
Lisp
Scheme Factorial function
ML/SML & Haskell
Python
C++ (define fac
Applications of FPLs
ILs vis-a-vis FPLs (lambda (n)
Haskell (if (= n 0)
Lisp 1
Scheme (* n (fac (- n 1))))))

Principles of Programming Languages Partha Pratim Das M03.60


Scheme - Lambdas and Functions

Module M03

Partha Pratim
Das (let ((x 5))
Functional (define foo (lambda (y) (bar x y)))
Programming
Functional Design
(define bar (lambda (a b) (+ (* a b) a)))
Functional
Programming
(foo (+ x 3))) => 45
Importance of FP
Examples of FPLs
Lisp ---------------------------------
Scheme
ML/SML & Haskell
(define reverse-subtract
Python (lambda (x y)
C++
Applications of FPLs
(- y x)))
ILs vis-a-vis FPLs
(reverse-subtract 7 10)
Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.61


Scheme - Lambdas and Functions

Module M03

Partha Pratim
Fibonacci Series
Das ------------------------------
Functional (define fib
Programming
Functional Design
(lambda (n)
Functional
Programming
(if (= n 0)
Importance of FP 0
Examples of FPLs
Lisp (if (= n 1)
Scheme
ML/SML & Haskell
1
Python (+ (fib (- n 1)) (fib (- n 2)))))))
C++
Applications of FPLs
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.62


Scheme - Lambdas and Functions

Module M03

Partha Pratim
GCD
Das ------------------------------
Functional (define gcd
Programming
Functional Design
(lambda (a b)
Functional
Programming
(if (= a b)
Importance of FP a
Examples of FPLs
Lisp (if (> a b)
Scheme
ML/SML & Haskell
(gcd (- a b) b)
Python (gcd a (- b a))))))
C++
Applications of FPLs
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.63


Scheme - Input / Output

Module M03

Partha Pratim
(+ 3 (read))
Das

Functional (display (+ 3 (read)))


Programming
Functional Design
Functional
Programming
Importance of FP (define prompt-read (lambda (Prompt)
Examples of FPLs
Lisp (display Prompt)
Scheme
ML/SML & Haskell
(read)))
Python
C++
Applications of FPLs
ILs vis-a-vis FPLs

Haskell

Lisp

Scheme

Principles of Programming Languages Partha Pratim Das M03.64

You might also like