0% found this document useful (0 votes)
19 views47 pages

FP Unit2

The document provides an overview of functional programming concepts including lambda calculus, data types, and pattern matching. It discusses the origins and goals of lambda calculus and outlines the basic rules. It then covers creating lambda functions in Haskell and Python, defining and manipulating lists, dictionaries, sets and strings in both languages. The document also discusses identifying patterns and performing pattern matching as well as regular expressions. Key list operations like creation, evaluation, filtering are demonstrated for both Haskell and Python.

Uploaded by

Dimple Gulla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views47 pages

FP Unit2

The document provides an overview of functional programming concepts including lambda calculus, data types, and pattern matching. It discusses the origins and goals of lambda calculus and outlines the basic rules. It then covers creating lambda functions in Haskell and Python, defining and manipulating lists, dictionaries, sets and strings in both languages. The document also discusses identifying patterns and performing pattern matching as well as regular expressions. Key list operations like creation, evaluation, filtering are demonstrated for both Haskell and Python.

Uploaded by

Dimple Gulla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Functional Programming

Prepared By
Ms.Afreen Fatima Mohammed
Ms.Deepika
Lambda Calculus/Data Types/Pattern Matching

Unit – No-2
Objectives
• Know the Origins, Goals and Tenets of Lambda Calculus
• Understand the rules for using Lambda Calculus
• Perform Reduction Operations
• Create lambda Functions in Haskell and Python
• Define, create, evaluate List and perform list manipulation in Haskell and Python
• Understand Dictionary, Set and String operations in Haskell and Python
• Identify Patterns and perform Pattern Matching in Haskell and Python
• Understand Regular Expressions
Lambda Calculus
• Origins, Goals and Tenets
• Understanding the Rules
• Performing Reduction Operations
• Creating Lambda Functions in Haskell and Python
Origins, Goals and Tenets

Origins
• Alonzo Church originally created lambda calculus in the 1930s

Goals
• Study the interaction between Functional Abstraction and Function Application

Tenets
• Lambda calculus uses only functions — no other data or other types
• Lambda calculus has no state or side effects
• The order of evaluation is irrelevant
• All functions are unary, taking just one argument
Understanding the Rules

• Creating functions to pass as variables


• Binding a variable to the expression (abstraction)
• Applying a function to an argument
Functions as variables
Lambda Function Read as
(M)N The input N is applied to the function M
M2(M1N) The function M1 is applied as input to M2 and that N is
applied as input to M1
EFG E is applied to F and F is applied to G or ((E)F) G
Examples

Pseudo code Lambda Calculus form Read as


inc(x) = x + 1 (x) -> x + 1 variable x is mapped to x
+1
Square_sum(x, y) = (x2 + y2) (x, y) -> x2 + y2 the tuple (x, y) is mapped
rewritten as to x2 + y2
x -> (y -> x2 + y2)
Abstracting Untyped Lambda Calculus
Function Definition Untyped Lambda Description
Calculus
f(x) = x + 1 λx.x + 1 λx.x is a lambda term
f(x) = x2 + y2 λx.x2 + y2 The variable y is
considered as a function
that isn’t yet defined,
not a variable
declaration

λx.(λy.x2 + y2) Provides the abstraction


Abstracting Simply-typed calculus
Untyped Lambda Typed Lambda Calculus Description
Calculus
λx.x + 1 λx:ν.x + 1 the parameter x has a
type of ν (nu), which
represents natural
numbers

If v takes int datatype λx:int.x + 1

λx.(λy.x2 + y2) λx:v.(λy:v.x2 + y2) Assign natural numbers


as the type for the sum
square function
Currying
Untyped Lambda Typed Lambda Calculus Description
Calculus

λx.x + 1 (λx.x + 1):ν -> ν Defines type for the function


as a whole rather than for x

λx.(λy.x2 + y2) (λx.(λy.x2 + y2)):ν -> ν -> ν Each parameter appears


separately, followed by the
output type
Reduction Operations
• α (alpha)
An act of renaming variables

• β (beta)
Replace variable with an argument

• η (eta)
No argument is applied to a variable
Lambda Functions in Haskell
Haskell Description
add = \x -> \y -> x + y type add 1 2 and press Enter.
The output is 3.

(+=) = \x -> \y -> x + y code creates a new operator, +=.


Or type 1+=2 and press Enter.
(+=) = \x y -> x + y The output is 3.

Creates a new operator


Lambda Functions in Python
Python Description
add = lambda x, y: x + y Type add(1, 2), execute the code,
Output is 3

add = lambda x: lambda y: x + y Type add(1)(2) , execute the code


Output is 3

Overrides existing operator


Data Types
• List

• Dictionary

• Set

• String
List
Operation Haskell Python
Create let a = [1, 2, 3, 4] a = [1, 2, 3, 4]
let b = [1..12] b = list(range(1, 13))
let c = [x * 2 | x <- a] c = [a * 2 for a in range(1,5)]
List Evaluation Operations in Haskell
Operations in let a = [1, 2, 3, 4, 5, Description Result
Haskell 6]
Evaluation a !! 0 Returns the first 1
value in list a at
index 0
head a Shows the value at 1
index 0
tail a Shows the [2,3,4,5,6]
remainder of the
list after index 0
init a Shows everything [1,2,3,4,5]
except the last
element of the list
Operations let a = [1, 2, 3, 4, 5, 6] Description Result
in Haskell

Evaluation last a Shows just the last 6


element in the list
take 3 a Requires the number of [1,2,3]
elements you want to
see as input and then
shows that number from
the beginning of the list

length a Returns the number of 6


elements in the list
Operations let a = [1, 2, 3, 4, 5, Description Result
in Haskell 6]
Evaluation drop 3 a Requires the number of elements [4,5,6]
you don’t want to see as input
and then shows the remainder of
the list after dropping the
required elements

null a Determines whether the list is False


empty and returns a Boolean
result which is in this case

minimum a Determines the smallest element 1


of a list and returns it
Operations let a = [1, 2, 3, 4, 5, 6] Description Result
in Haskell
Evaluation maximum a Determines the largest 6
element of a list and returns it

sum a Adds the numbers of the list 21


together
product a Multiplies the numbers of the 720
list together

avg = \x -> sum(x) `div` Use the sum and length 3


length(x) functions to determine the
avg a average value in a list
List Evaluation Operations in Python
Operations in a = [1, 2, 3, 4, 5, 6] Description Result
Python
Evaluation a[0] Returns the first value in 1
list a at index 0
a[1:] Obtains the tail of the list [2,3,4,5,6]
a[:-1] Obtains all but the last [1,2,3,4,5]
element
a[-1:] Obtains just the last 6
element
a[:-3] Performs the same as [1,2,3]
take 3 a in Haskell
Operations a = [1, 2, 3, 4, 5, Description Result
in Python 6]
Evaluation a[-3:] Performs the same as [4,5,6]
drop 3 a in Haskell
len(a) Returns the number of 6
elements in a list
not a Checks for an empty list.
This check is different
from a is None, which
checks for an actual null
value
min(a) Returns the smallest list 1
element
Operations a = [1, 2, 3, 4, 5, 6] Description Result
in Python
Evaluation max(a) Returns the largest list 6
element
sum(a) Adds the number of 21
the list together
from functools import reduce The lambda function
reduce(lambda x, y: x * y, a) multiplies the current
list element, y, by the
accumulated value, x.
Operations a = [1, 2, 3, 4, 5, 6] Description Result
in Python
Evaluation prod = lambda z: reduce(lambda x, To find the product of 720
y: x * y, z) list a, you would type
prod(a)
avg = lambda x: sum(x) // len(x) The use of the // 3
avg(a) operator to perform
integer division
Common List Manipulations
•Concatenation
Adding two lists

•Repetition
Create specific number of duplicates of a source list

•Membership
Check whether an element exists within a list

•Iteration
Interacting with each element of a list individually

•Editing
Inserting/Removing/Reversing/Sorting
List Manipulation in Haskell
List List manipulation Function Output
let a = [1, 2, 3, 4, 5, 6] reverse a [6,5,4,3,2,1]
splitAt 3 a ([1,2,3],[4,5,6])
filter odd a [1,3,5]
let b = [7,8,9] a ++ b [1, 2, 3, 4, 5, 6, 7,8,9]
zip a ['a', 'b', 'c', 'd', 'e', 'f'] [(1,'a'),(2,'b'),(3,'c'),(4,'d'),
(5,'e'),(6,'f')]
List Manipulation in Python
List List manipulation Output Description
Function
a = [1, 2, 3, 4, 5, 6] a.reverse () a=[6,5,4,3,2,1] Modifies the
original list a
reverse = lambda x: x[::-1] a = [1, 2, 3, 4, 5, 6] The original list
b = reverse(a) b=[6,5,4,3,2,1] is not modified
Dictionary
• Python
• myDict = {"First": 1, "Second": 2, "Third": 3}

• Haskell
import qualified Data.Map as M
let myDict = M.fromList[("First", 1), ("Second", 2), ("Third", 3)]
import qualified Data.HashMap.Strict as HM
let myDict2 = HM.fromList[("First", 1), ("Second", 2) ("Third", 3)]
Set
• Python
• myFSet = frozenset([1, 2, 3, 4, 5, 6])

• Haskell

import Data.Set as Set


let mySet = Set.fromList[1, 2, 3, 4, 5, 6]
String
Python

• String is immutable
• min(myString) returns the space
• max(myString) returns r to process string

Haskell

• Uses String specific libraries Data.String


String
Programming String Output
language
Python myString = "Hello There!" Hello There
Haskell let myString = "Hello There!” myString is of type [Char],
:t myString a character list
Pattern Matching
• Looking for patterns in data
• Regular Expressions
• Pattern Matching in Python and Haskell
Patterns in data
• Organizational patterns
• Progression patterns
• Transitional Patterns
Regular Expressions(RE)
• Special characters
• Wildcard characters
• Anchors
• Delineating sub-expressions using grouping constructs
Special characters

• Control character
Provides access to control characters such as tab (\t), newline (\n), and carriage
return (\r)

• Numeric character
Defines a character based on numeric value like octal (\nnn), hexadecimal (\xnn),
and Unicode \unnnn)

• Escaped special character


\( would specify an opening parenthesis rather than the start of a sub-expression
Wildcard characters
• .
Any character (with the possible exception of the newline character or other control
characters)

• \w
Any word character

• \W
Any nonword character

• \s
Any whitespace character
Wildcard characters
• \S
Any non-whitespace character

• \d
Any decimal digit

• \D
Any nondecimal digit
Anchors
• ^
Looks at the start of the string

• $
Looks at the end of the string

• *
Matches zero or more occurrences of the specified character

• +
Matches one or more occurrences of the specified character. The character must
appear at least once.
Anchors
• ?
Matches zero or one occurrences of the specified character

• {m}
Specifies m number of the preceding characters required for a match

• {m,n}
Specifies the range from m to n number of the preceding characters required for a match

• expression|expression
Performs or searches where the regular expression compiler will locate either one
expression or the other expression and count it as a match
Grouping Constructs
• [a-z]
Look for all lowercase characters between a and z

• [az]
Look for just the letters a and z, but nothing in between

• [^a-z]
Look for everything but the lowercase letters a through z
• [x]
Look for a single character from the characters specified by x

• [x-y]
Search for a single character from the range of characters specified by x and y

• [^expression]
Locate any single character not found in the character expression
Pattern Matching in Haskell
• Uses Text.Regex.Posix package

• Matching a telephone number with Haskell


let tel = "\\([0-9]{3}\\)[0-9]{3}\\-[0-9]{4}”

• Output
Telephone number: 555-555-1234
Pattern Matching in Python
• Uses re library

• Operations
re.search, re.match, re.findall, re.split

• Matching a telephone number with Python


tel = "\(\d{3}\)\d{3}\-\d{4}"

• Output
(555)555-1234

• To test this pattern, type re.search(tel, testString).group() and press Enter


Summary

• Lambda Calculus
• Data Types
• Pattern Matching
References
[1]. John Paul Mueller, “Functional Programming for dummies”, A Wiley Brand, 2019
Edition
[2]. https://wiki.haskell.org/Regular_expressions
[3]. https://docs.python.org/3.6/library/re.html
[4]. https://www.regular-expressions.info/
[5]. https://docs.python.org/3.6/library/re.html#match-objects

You might also like