Functional Programming 2.1
Functional Programming 2.1
• sum(3, 1) returns 4
• Immutability helps us to avoid various
problem.
• Immutable objects are more thread safe.
• If you are in concurrent programming
immutability makes your task simple and easy.
What is Recursion?
• That's it. You can print your result by calling this function.
• println(myResult(65))
• The 'if' statement returns a value hence we
don't need a variable. The functional version
of the code is concise, and the returning
statement helps us to eliminate variables and
achieve immutability.
Strict and Lazy Evaluations
• Functional Languages
– Pure functional languages does not have variables
– There is no “state” in functional programs
– There are no side effects
– Repetition is through recursion
Functional Language Examples
• LISP
• Scheme
• ML
• Haskell
• OCaml
• F#
Mathematical Function
• A mathematical function is a mapping of
member in domain set to a member in range
set.
Simple Functions
• Function definitions are written as function
name followed by a list of parameters in
parentheses.
Ex: cube(x) = x * x * x
Ex: cube(2) = 2 * 2 * 2 = 8
Simple Functions (cont...)
• A lambda expression is a method for defining nameless functions.
Ex: λ(x)x * x * x
Notation: h=fog
Ex: h(x) = x * x
then α(h, (2, 3, 4)) yields (4, 9, 16)
LISP
• LISP is the first functional programming language.
• List elements are pairs, where the first part is the data of
the element and second part can be a pointer to an atom, a
pointer to another element, or the empty list.
LISP (cont...)
• Lists are specified in LISP by delimiting their
elements with parentheses.
(+ 5 7) yields 12
(+ 3 4 7 6) yields 20
LISP Interpreter (cont...)
• The lambda notation was chosen to specify function
definitions.
Ex:
(DEFINE (square number)
(* number number))
(square 5) yields 25
Scheme : Numeric Predicate Functions
Ex:
(DEFINE (factorial n)
(IF (<= n 1) 1
(* n (factorial (- n 1)))
))
Scheme : Control Flow (cont...)
• Example on COND selector:
• The CAR function accepts a list and returns the first element in the list.
• The CDR functions accepts a list and returns remaining elements in the list except
the first element.
Ex:
fun circum(r) = 3.1415 * r * r;
fun times10(x) = 10 * x;
fun square(x) = x * x;
• Function call:
square(2.75);
ML (cont...)
• Types can be specified as follows:
Ex:
fun fact(n : int) : int = if n <= 1 then 1
else n * fact (n – 1);
ML (cont...)
• ML supports lists and list operations.
let
val radius = 2.7;
val pi = 3.14159;
in
pi * radius * radius;
end;
ML (cont...)
• The map function takes a single parameter, which
is a function. The resulting function takes a list as
a parameter and applies the function to each
element in the list.
Ex:
fun cube x = x * x * x;
val cubeList = map cube;
val newList = cubeList [1, 3, 5];