Functional and Logic
Programming Languages
Syllabus
Introduction to lambda calculus ing language
i fundamentals of functional programm
Programing with Scheme - Programming with ML.- Introduction ta logic and loge prog
Programming with Prolog - multiparadigm languages
Contents
5.1 Introduction to Lambda Calculus
5.2 Fundamentals of Functional Programming Languages
53 Programming with Scheme
5.4 Programming with ML
5.5 Introduction to Logie and Logic Programming
5.6 Programming with Prolog
5.7 Comparison between Functional Programming and Logical Programming
‘and Object Oriented Programming Languages
58 Multi-paradigm Languages
5.9 Two Marks Questions with AnswersFunctional an ogi PAM Laren
ning Languay
El introduction to Lambda Calculus
© The lambda calculus is a formal system for
‘computations based on functions. i
‘Any function which is expressible in the mathematical form 18 als e*Pressibie ww
lambda calculus. 5
© The lambda calculus is first formulated by Alonozo Church to expr
1 expressing the matherna
computations with functions
‘The name lambda is derived from the Greek letter 2. which is used to denote the
binding of variable in function. The letter is arbitrary and basically has
‘¢ Many functional languages like ML, LISP, Haskell are based on lambda calculus,
no meaning
‘Syntax of Lambda Calculus
The syntax of lambda calculus is very simple. It can be denoted in BNF form as
expr 0 (
-)
| ( )
|
|
‘+ The first rule is called lambda abstraction. It is used for building new functions
Parentheses can be used to indicate that some part of an expression belongs
together.
The second rule represents the function application. The function application
‘means evaluating the function by substituting the values. The expression can be in
any form, It can be there in prefix, postix or infix form. As LISP makes use of prefix
expression form, many times the lambda calculus is expressed with prefix notation
But one can make use of infix form of expression for convenience.
‘The third rule represents the variables. The variables can be any like a, b, ¢ 4, x.y
and so on.
‘The forth rule represents the constant. The constant can be some value such as 0, 1,
2 or predefined functions such as +, * and so on.
For example
¥
Head Body notner
wih varable or Expratsion ®¢pression used
1 forfunciones
a
Derivation of (Ax -( + 1 1) 8)is called lambda term.
4697 9S vatlabe > eape sy
sy substituting let most symibg
Sx-< ‘expr >)
20x
always, we get
(expr>)
= Ox: (( )< er)
= (x: ((< variable > < expr >) ))
= (x: ((x) ))
= (ox (x4) ))
= (x: ((X +) ))
=x a
> 0x: +1)
+ The parenthesis are needed for function application to eliminate ambiguity
+ According to syntax description (2x: +1) should be written as @X- (4+ 1).
+ But in order to increase readability we omit parenthesis, if there is no ambiguity in
the expression.
EEE Lambda Abstraction
The lambda abstraction is 2 wa
cevariable> - Princes of Programming anguages__5-#
metavariables ranging over lambda expression.
The function application associate
1 £2 E3 means (E1 E299)
3. The Av ETE2ES means (x (EIEZE
“Thus function application has ger
4. The series of abstraction can be interpreted a5 follows ~
yz means (Ay QE
the lambda expression itself denotes the function For example wie
function can be denoted as Twice = (if (AX (9)
to the left
and not ((x-E1E2)E9)
precedence than the 2
jpstraction.
Free and Bound Variable
# In calculus, all the names are local to definitions.
In the function Axx we say that xis bound since its occurrence in the body ofthe
definition is preceded by 2x
‘A name not preceded by 1 is called free variable.
+ For example -
xx)
‘The variable x is bound variable whereas y isa free variable.
‘The same variable can appear many times in the different context. Some instances of
the variable may be bound whereas other are free.
‘+ For example -In the expression
y+ y) Qooxy)
The variable y in the body of first expression from the left is bound to the first A. Hence
vis said to bound in first expression. Whereas variable x is bound to second lambda in
the second expression but y is free. Hence in the second expression x is said to be bound
variable while y is said to be free variable.
Note that y in second expression is totally independent of the y in the first expression.
Substitution
While simplifying the lambda calculus, forthe expression (x-E) T the argument T will
be substituted for x in an expression E.
The substitution of a term T for a variable x in E is written as (T/x} E. It can be read as
4 occurrences of x in expression E by the term T.
replaceeset Propram ing
There are ae eee
iederstand them that a tone end Lape Programing Largueoes
Te follow
With the he} wed while s
Ine%0N othe oloning SP of eames performing the substitution, Let
case,
'S XPressior
cxtipresnon F !ONE has no bound occurrences
ml
Prox
Repiace’x in Eby,
Replace x in
E bye
(txt (09) = (ety
Similarly, we can obtain the values -
3.UsHexy)= ty)
4. (JdJ/NIx = Goo)
Rule 1 : If the free variables of T has no bound occurrence in E then T replaces all
occurrences of xin E to form {TIxIE.
In the following cases, expression E has no free occurrences if x.
1. (tsly
Here expression E contains y and no free occurrence of x. Hence the result will be
E itself. Similarly -
texy(* zy) = 29)
3. (uxlayy) = @yy)
Rule 2: If E has no free occurrence of variable x. then (T/x} = Eis E itself.
In following case
Rale 3, The fre variable ts in T has a bound occurrence in , Then expression Eis
* onmed by renaming bound occurrence of tin E
For example
1 uaiaesy=?Functonal and Loge rex
———rssmeerpuiges 5-6 Funatone/ end Ln ae
We will introduce a new variable for it as 12. Then replace the
by t. Then the expression becomes,
Dtini(tx) = [atixen)= zt)
Similarly,
2. [Walee) = (tx@zz) = 0x2)
CERES tie towing using substitution
VOxx 2 i) xy) 2 i) (Axyx) 20
io) xa) (yy) v)(axtayy)
Solution:
DOxxdz
Here is a bind variable and body of & expression is x. The statement for evaluation
can be read as replace x by z and throw-away Ax.
Oxxz =z
i Oxyd z
Here x is bind variable
binding of x with o
OfyS)2) = aye
: Oxyx)z = ayz
iif) Oxyd zu
Binding variable is, substitute xby 2
Oy2)u
As the binding v.
substitution takes pla
and y is free, We will substitute x by 2. Then we will eliminate
‘riable is y and there is no
ce and we get expression itself
Qy2yu 2
Bow) yy)
¥ im expression (body), Hence no
Clearly \ is a binding variable,
Place Ay-y tor each x
=O
ayy)
Now visa binding variable. We replace yby ayy
= ayy)prope or Homan Lanpuaey
0x09) 2) Oy 22 netent na toe Programming
yor the binding
Variable y we
prown away, ¥ We have substituted variable 2. Due to which Ay will Be
Now the term become:
romes (Ax. 2
pethe term (x2) iteepy on™” 2) Bu asin this erm binding variable is x- the result will
BE Peta conversion
‘The basic operation in la
‘mbda calculus isthe application of expression. For example
(x +1))) is equal to
alto. +1 variable x
anton the labs TNE ME ae singh val 3 forte vas
aaa called beta conversion.
ersion is
lambdas. 'on i a process of simplifying the expression and this removing the
‘There are two approaches for applying beta conversion
__1.Pass by value 2. Passby name
Let us discuss them with the help of examples -
4.8
by value
Consider following expression in which evaluate an expression with arguments (° 3
first and the result of evaluation is substituted,
Cae
Note : Number of opening brackets are equal to number of closing brackets.
‘The B is used to show evaluation steps
So,
oxen)
an
oxi a>
wide
2. Pass by name
ig method we does not evaluate the expression in early stage. The argument
fated directly and at the end when the situation arises such that we
ther then evaluation is done.
Int
expression is substi
can not substitute furl
sree gna aso called a8 delayed evaluation or outermost evaluation or normal
orderPrneples of Progamming Lanpunges 5-8
xis ay)
Wxeede
The call by value reach a normal form faster than call by name. That means fewer bts
reductions take place in call by value
Verity the flowing equalities
ASIN =] where Sis Axyz(xz) (yz) and Lis 2x
i twice vice) £ =p ((F (6),
where vice is At ffs)
Solution:
i)Let,
SUil=s Gexyz(xzy(yzlM),
This isthe value
of S (Given)
SI is
root
ran nl an
(exyz-xz(y2)) (xx) Boe) (ie)
Now we will apply f reductions. But before that we will rename bound variables.
xyr2{y2) (docx (boc) xn) mp (anya x2(92)) (230 0) (XII) =
Now rename underlined tuple
(axyzxalyz))(huuy(avv)Q%x) =p
Rename underlined tuple
Gaxyzxztyz))uuyavvy(e (a)
Now we will solve equation (1)
any xaly2)) (a wyv-vytt) =p
Place Jur for x as xis bind variable
Then eliminate x from hxy2.
¥)\
ayz-(ausn)z{yz (Av vit) =
Gayzztyz avs)ve tA) for binding variable»
\ezz beomes
Bene
ate
trwe rename ty then,
At davst
Sllls3 Lis proved
ii) The twice function is defined as twice = Af Qi)
twvice (tice) £
= twice twice
= hice f (twice f)
= twice ff (E00)
= Hie)
FEMI co vtiotvie atowing
BAX Ax + XD) DS
fi) (Ax Ay -4N(Ax
Solution :
i) x Grt(enD) DS
Gotan?
Ges De
52)
r
bev
i Govdy-an(Qx-r978
10 acyl “5 (away -¥5)7 8)
18)
ante
oxi)
28)
eevee
L
0= Support these rule
Explain the syntax of lamba ccs in te form of BNF ral a
deriving some lamiada expression.
Explain the concept ambea abstraction.
Explin wth suitable istration in oda coc the concept of
Explain th rules used or substitution inl alee 0th stations
Write a short note on beta conversion in lambda calculus
ee and bound variables,
EJ Fundamentals of Functional Programming Languages ;
/ © Functional languages are those languages in which the basic building block
fanctions, awid she
‘* In functional programming the programmer is conce!
and not memory related variable storage and assignment sequence.
.med only with functionality
Features of functional programming language
1. The functional programming languages are modelled on the concept of
mathematical functions and make use of only conditional expressions and
recursion for the computational purpose.
2. The programs are constructed by building functional applications. That means,
the values produced by one or more functions become the parameters to another
functions.
3. The purest form of functional programming languages use neither variables nor
assignment statements, although this is relaxed somewhat in most applied
functional languages.
4, The functional languages can be categorized in two types - Pure functional
languages and impure functional languages.
a. The pure functional language support only functional paradigm. Example of
pure functional language is ML, Haskell.
b. The impure functional language can be used to write imperative style
programs(For example C is a imperative style programming language).
Example of impure functional programming language is LISP,
ommonly used functional programming languages:
LISP, S
sal, Haskell, ML, APL, scheme are some commonly used functional languages.The main domain of pene nm
an guagE is used
na
ental Programmin
machine leami, for building 3g language is artificial intelligence
1 Natural lang a8 NPEM sYstems, knowledge representation,
‘Sage processing, modeling speech and vision.
> Functional languageis aac
for bu
ding mathematical software.
‘ame the commonly used
te the applications of finctond ye
tonal prog
B)Programming with Scheme
_senetsa dle ip among ge Sees
ass rare at the MIT Al Lab and released by its developers, Guy L. Stesle and
Gerald Jay Sussman.
Features of scheme
1) Tthas ability to evaluate its own code natively
2) It contains a full set of numerical data.
5) Tt has shared namespaces for variables and procedures, That means, SAN"
primitives used to operate on variables can operate On ‘procedures and functions
as well.
|4) The bindings of all variables in scheme are determined by the unit of code that the
variable appears. Thisis known as lexical scope
sg) The scheme has 2 macro system that owe the programmer to extend the
functionality of the language ‘without interfering with the language's native
inetionalit
syntax.
Pere re nity 0a standard procedures and functions
eter
5 scheme InterPr ;
ExT Tre jnnerpreter is. 2 read-evaluate-write infinite loop, That means the
+The scheme lyre on exresson cemtered by user, interprets it and
interpreter"
displays Ine interpreted by the function EVAL
«ExpressionPrmcpes of Programming Languages __s-12_Furctonel end LOE
. » evaluated 35 - firstly, each of the
Expressions that call the primitive functions are evaluated hi
Parameter expressions are evaluated. Then primitive
Parameter values and result is displayed on the interpreter.
function is applied to
Primitive Numeric Functions
Expressions can be created with the help of operators. There are
‘operators such as +, -, * and used for manipulating the scheme, Following ill
use of operators
>(+23)
5
(23)
6
>¢53)
‘
> (423-53),
10
farious arithmetic
ustrates the
Note that the evaluation of expression is based on prefix notation. Prefix notation is a
notation in which operator comes first and then two operands appear. For instance +23
will be converted to 2 +3 and result of operation will be 5.
Defining Fuinctions
In scheme we can define a nameless function called lambda function. For example -
[enon
> (Clambda (x) (* x x)) 12)
144
Here variable x is called bound variable.
Similarly, we can define user defined function using define. The syntax is
(define function_name parameters)
(expression)ones of Programming Ly
oeample
weean define
ne the function na,
get edd num sug) CM add as
om) rum2) follows -
Languages
)
Now, We can call the
somumbers ‘Bove fancton with two parameters fr performing ation of
{084 10 20) Pa rs for perf 8
2
Write a fun,
solution =
> (define cubs(a)
Output
(REESE Write procetie to cisplay su of squares.
Solution :
> (define square(x)
x0)
> (defun sum-of-square(stat end)
(i> start end)
°
(4 (equate stan) (sum-of-aquara(+ 1 tat) end)
)
I output
> (eumof-equare 1 6)
5s
‘Output Functions
function 15 Use
ction i usin
. 4 to display some message or result of expression on the
ences g the keyword display. The syntax for output
Ninerpreter, The output
ae
aPrinciples of Programming Languages 5-14 __Furetonel and PETES Yay
For example
> (display (+ 23)
5
Similarly we can display the text message using display. For example -
> (dlsplay “Weicorne')
Welcome
‘The newline can be entered with the help of display functio
> (newline)
Jn as follows -
Numeric Predicate Functions
‘A predicate function is a function that returns boolean value either true(=
Operator Purpose Example
< Less than, Itreturns true if first operand is (< 1020
less than second argument.
> Greater than, Ie returns true if first operand
is greater than second argument
= It first operand is equal to second operand
then it returns true .
Less than equal to,
>= Greater than equal to
Is even number
odd oxkd number ote?
Ist revo?¢
ring
SPemrme rae: 5.15 peu ma ige Pager ea
EE contro! Flow =
There are two
fwo important control flow stat
low statements -
4, IF Statement
The if is a two-way
ai) Then expression and ii
The syntax is
(ifptedicate then expression else expression)
For example -
> (f(> 1020)
(display “10 is greater than 20°)
(display "10 is lesser than 20)
)
1018 lesser than 20
selector function. It has three parts — i) Predicate exp}
i) Else expression.
2, COND Statement
‘The cond is a multiple selector which is based on mathematical expression. Ths
of cond statement is as follows -
(cond
(predicate_1 expression)
(predicate_2 expression)
(predicate _n exp
(else expressicn!]
Here, else is optional clause
For example ~
Sent
{C10 10) play "1018 roar an 1
{(< 10 10) (aispiay “10 Ls Re ie
(else (display "30 # ‘equal to 1¢
)
The output willbe
Oia equal 10roche otPepanmngagieges 5.18 ___—_—Furtnsa os AESLay
List Functions
‘| The car returns first element of a non empty list
For example -
> (ear 234)
1
‘© The cdr returns rest of the lst after the first element is removed. It is pronounced as
couldcer.
> (oie (12349
as)
* We can combine two lists using cons. The cons fur
returns a new cons cell containing the two values
> (eon 1020 3040)
(1020 0 40)
Write sequences of CAR’
following sexpresion :
1) (apple orange pear grapes) it) (apple orange) (pear grapes)
itt) (apple orange) (pear) (grapes)))
Solution :
4) (car(cdr(cdr'(apple orange pear grapes))))
ii) (car(car(ede'((apple orange) (peat grapes)))))
ily (can(car(car(cdr(cdr(apple (orange) (peat))((grapes)))))))
mnction takes two arguments and,
sand CDR’s that wil pick the atom pear out ofthe
Predicate Functions for Symbolic Atoms and Lists
(1) Equal (eq?) : It takes two arguments and if two arguments are equal then it returns
Ht otherwise it returns #f
> (oq? gh)
“
> (ea? 55)
*
(2) List(list?) : This predicate is used to test if the argument is list or not. If it is list then
it returns #t otherwise it returns #f
For example -
> (it? (10 20 309)
*
> fist? 10)©) Nulinutir,
tt (102 a, functors na tage Programming Languages.
ee “to check itis empty list oF not.
Hf the arg
otherwise it retums #f
Explain with
With the help
Explain mum PP I uital example how to
meric predicay
torte a function in scheme ?
What are the types of
functions used in scheme
control flow st
fatements used in scheme ? Explain
ind CONS ?
EB} Programming with ML
What is CAR COR a
© ML is also known
a ‘own as SML. The long form is Standard Meta Language. Itis a type-safe
Programming, functional programming language
The difference betw
‘een ML and scheme is that ML is strongly typed language whereas
scheme is a typeless, aannanianer acamnncan alae
Features of ML.
* ML isa static scoped functional progeamming language.
© The syntax of ML programming language is more like imperative programming,
language.
Everything is built from expressions.
It provides for structured values such as ists, tuples and so on.
‘Simple Declarations
We can evaluate simple expressions using ML for example -
@@@ Standard ML ofNew)
= 10+20; ,
val it = 30: intSe —t
Similarly,
WE Standard ML of New)
~ val x = 2434u;
val x = 1d: int
For example on declaring the
ated as follows =
We can get the name of the data types as follows -
integer, string data we get the name of data type. Its illust.
WH Standard ML of New)
- 10;
val it = 10: int
= "hello
val it = "hello" : string
- 10.56;
val it = 10.56 : real
jinding Expressions
Binding allows us to refer to an item as a/symbolic name,
Here variable ais assigned with the value 20. This variable a can be adde
we get the value 35,
ed to 15 and
eeeBB runction,
For example
fan cubetnine)
Following sere.
We can also specify the return type to this function. For example
fun cubstcint)ine
REIDSISREEE ite o Mprgra to find factorial of given numer
Solution : The function definition is as follow
fun fact(nsint)int = if = Orbea
ise n*tact(n-th
‘The function call is as follows -
fact(S); //ourput:120
[REMIT cee ML prose nt
Solution
cme
ign = Other
‘tan fb(nint):
pp(e-1) +822
‘The call to the function |=
f(3), /outper?
complexities ot F
wat without usin;
set [] with the elements separatedPrinciple
9 Lan,
tonal and Loge Prog
St Fregramming Languoges 5-20 ___—Functonal and Logic Progr
“ot Frepremming Languages 5-20
‘There are two constructors in st = (1) Empty ist (2) Cons operator represented y
“The nil constructor is the ist containing nothing. The operator: takes an item, m the
left and a list on the right. F
‘or example -
@ Standard ML of News
> lirnil;
val it = [1] : int list
2nd
val it = [2,1] : int list
> 3::Q2::Ctinily);
val it = [32,1] : int list
‘There are some built in functions associated with the list. The hd returns the head of
the list and tl returns the tall ofthe list. That means the hd returns the first element of the
list and €l returns all bu the first element of the lis.
@ Standard ML of News
- hd[1e, 20, 30];
val it = 10): int
~ tl{10, 20, 30,49];
val it = [20,30,u0]': int List
Writes ML rose ippena st tw eiting tn The nome rrenrc omFunctional and Loge Programmang Languages
Function Definition
tstepenta) Toa
= sete nenataan
vansnaano
Function Definition
fun reverse(man) = if null) thon n
se reverse(t(m) hoa),
Funetion call
reverse({10,20,30,401,0;
(40,20,20,10) //ourput
Write a MEL program to find the length of st.
Sotution :
Function Call
‘un nl) = 0
= [en(a:x
Hens);
Function Definition
len({10,20,90,40,501)
eae
ist the features of ML-
ee er defined function in ML ? Explain it with the help of example.
duction to Logic and Logic Programming
— ming is a programming paradigm in which the set of sentences are
problem domain.
aah PURI IEATIONS® aProgranring Larges
Princip
rine of Programming Languages 0-22 Functions nd bn
sntrolled deduction.
separation of programs
+ Logie prog be viewed
ing
* An important concept in logie programming, is the to their
logic component and their control component.
+ Kowalski illustrates the logic programming by following equation,
Algorithm = Logie + Control
represents a logic program in the form of facts
implemented by applying the rules
where "Li and rules. The
“Control” represents how the algorithm can be
in particular order.
* The concept of logic programming is linked up
Prolog is acronym of PROgramming inLOGIC. «
rogramming with Prolog st") toc
An this section we will get introduced with some basic features of logic programming
using prolog. The programs in prolog can be implemented and tested using SWI-Prolog
systems. We can get the interpreter for the prolog from _www.s
prolog.org/download/stable. Choose the appropriate binaries depending upon your
with a language called prolog.
wo FFE
operating system version,
‘The interpreter window appears on which-? is a prompt. We can type and test various
simple prolog statements on this prompt window. Here are some sample examples of
execution and testing of SWI-Prolog
ST
Sibmereere Menu eee
[ecsmentreesioa
. |
| Forhet, use? hep Topi) a? aprozos(Wons)
}
rio
| ne
bonzmn frauds - Ap }
| tose
| 3.2. wate(Envoy Protogt’) - |
| borrow"
Note that every statement in prolog must be terminated by dot.Prolog is used in arti
Problems. "ficial intelligence and expert system to solve com
2) Wis used
©” pattern mat
3) Itis used to develop hatching algorithm.
4)
Prolog is vag ets son object vented concepts
dese © build decison sport systems that at organizations 9
'N8: For example - Decision systems for medical diagnoses.
EBD Basic Building Blocks
Relations
+ Prolog makes u
Prolog makes use of elation instead of using fumeios. elton ate more Hexible
‘teats the arguments and results uniformly.
+. For example - Consider following list
label
* As we know that the list can be considered as (HIT]. That means in the list H Le
head occurs first and then comes Ti. tail. Hence prolog will teat [a,b,c] 25,
{a.b.e]= [a| [bee]
Queries
‘In prolog, the simple queries can be created to check whether particular tuple
belongs to a relation
«In below given execution, the first two queries represent the simple Hand T
relation between the members of the ist. Hence the answer fur out to be true or
yes.
© smrrows han ovsnaanon 2) aoe
fe eat Seting Run Crug Hee
32-pnd bib
a2 -pne Atos
sr-ped=tancital
4s But in the third query since d isnot the member of the lis [ab] the answer tum
out to be false,sm Funcuonal end Lope Programming Langues
* A prolog program consists of a mumber of clauses. Each clause is either a factor a
rule. After a prolog program is loaded (or consulted) in a prolog interPreter, users
can submit goals or queries and the prolog intepreter will give results (answers)
according to the facts and rules.
(1) Terms :
+ Prolog term is a constant, a variable, ora structure. A constant is either an atom or
an integer. Atoms are the symbolic values of prolog
‘+ A variable is any string of letters, digits and underscores that begins with an
uppercase letter or an underscore (_ ). Variables are not bound to types by
declarations. The binding of a value and thus a type, to a variable is called an
instantiation.
(2) Goals:
«A goal is a statement starting with a predicate and probably followed by its
arguments. In a valid goal, the predicate must have appeared in at least one fact or
rule in the consulted program and the number of arguments in the goal must be the
‘same as that appears in the consulted program. Also, all the arguments (if any) are
constants.
«The purpose of submitting a goal isto find out whether the statement represented
by the goal is true according to the knowledge database (ie. the facts and rules in
the consulted program). This is similar to proving a hypothesis - The goal being the
hypothesis, the facts being the axioms and the rules being the theorems.
(3) Fact,
«A fact must start with a predicate (which is an atom) and end with a fullstop. The
predicate may be followed by one or more arguments which are enclosed by
parentheses. The arguments can be constants, numbers, variables or lists
Arguments are separated by commas
«The syntax of fact is,
pred(arg!, ar92, .. arg)
Where
pred is the name ofthe predicate and argi, ..argN are the arguments
For example -
sman(anand),
‘manarun).omnanianuredha)
Troman\jayashres)
arenttanand perth), 5
‘means
Mecs(eniradta.pany) SMO! parent of pant
jtlanm snuradha}
psent avashree,enuradna,
‘The result as either
true or false
lepending upon the facts. It is as follows
2s
-Proog (Mulvnreaded version 72
version 7.22)
File Eat Seting Run Debug Her
12 - parentiana
Tee amen pec,
2.2 -parentiarun.am
22 -paren{arunanuradha}
37 - par
False
tarun,anan),
42
(4) Rule:
«A rule can be viewed as an extension ofa fact with added conditions that also have
te beatified for it to be true It consists of two parts, A rule is no more than a
stored query. Its syntax is
tnead :- body.
where
head is a predicate definition (ust ikea fact)
sis the neck symbol, sometimes read a5
body is one or more goals (@ 469)
For example -
facen(#c)-mnancF parent C)
Example using Fact and Rule
1p Pacts */
manianana) j
man(arst)
eet eee‘woman(anuradha),
‘woman(jayashree)
Parent(anand parth). % means anand is parent of parth
Parentianuradha path).
arent(arun anuradha)
arent{jayashree.anuradha)
("A general rule */
fatner(F.C)-man(F) parent(F.C),
‘mother(M.C):-woman(h0) parent(M.C).
ewe query
+? father(X part
The above query can be read who is father of parth ? The answer is X = anand is 3
father of parth.
Response to Query
Control represents how a language computes a response to-a query. The control
execution is based on two rules -
1. Goal order : That means choose the leftmost subgoal
2. Rule order: That means select the first applicable rule
|A goal is a statement starting with a predicate and probably followed by its
arguments. In a valid goal, the predicate must have appeared in at least one fact or rule in
the consulted program and the number of arguments in the goal must be the same as that
appears in the consulted program. Also, all the arguments (if any) are constants.
The purpose of submitting a goal is to find out whether the statement represented by
the goal is true according to the knowledge database (ie. the facts and rules in the
consulted program). Let us understand how control in prolog works with the help of
simple example. Following is a family.pl file in which the rules and facts are written.
‘-Rules*/
ofather(X.Y) father(X-2),parent(2,¥).
parentiXY): father(XY),
Facts")
{ther(dashrath,cam), Xmeans dashrath i father of ram
father(raghu.aja).
father(aja.dashrath).
father(ram,luv).
fesmeriraen inveh).‘The goals can
‘be executed on the prompt window as follows ~
12. gfameriaa ram
Uz vara
2 paremx yy
X= daswan,
{2am
3 7-tarerxy) tater amy
x ct
¥
2
asmath
Now consider the goal gfather(aja,ram).
‘As we know there are two rues for execution of contol -
1. Goal order : That means choose the leftmost subgoal
2. Rule order : That means selec the fist applicable rule
Here the mules are,
y= tater XZ) parent(2.¥),
parent(X.¥)= fatberOX%)
step 1: For gfather(aiaram) W
inter X19 jaxbertXZ)porent2.1)
ssabgoal ie father (XZ) is chosen firs.(Goal ordering)
apply the first applicable rule(Rule ordering)
ap 2: The match for father\2) 15 searched in the fact lst with X = aja. We wall find the
ed veijadashrath), Hence value of Z= dashrath,
match with fathe
eSPie Popwmnny pages 5.25 Pst as RSI en
Hence the first rule now becomes
tats) tari 2 pare. wit z=daabentn and YF
Step 3: For the subgoal parent(Z.¥) select the rule
Parent XY): father CY),
with X = Z = dashrath and Y= ram, The parent will retur™ “ihe
father(X. Y)efather(dashrath ram) which comes out tobe true. Hence we Bet the answer gy
true
While executing the control the prolog choose a rule PY»
i) Searching sequentially in the program from top to bottom whose Read matche,
with the goal with possible uniter.
fi) Remember the position of the matched rule.
i) Join the rule body in front of the sequence of sub goals to be solved,
iv) Repeat until either goal is satisfied or is failed.
Another example
Consider another example for goal ordering and rule ordering. Consider following
prolog database
Rule order affects tl h for solutions
Step 1
familyl.pl
/rRules*/
descend Y)- child),
descend XY): cild(X.2) descend).ponciles of Progra
peneiples SA Rrogemmning Languages 5
Now try out following queries
step 2: Now just change the ordering of the rules as follows
family2.pl
pRuies"/
sdeacond (X.Y): child(X.Z}.descendi2.¥).
deacend(X.Y):- child(%.¥).
Facts"!
cenuld(tuv ram).
child(ram,dashrath).
chid(dasbrath. aja).
child(aje rag)
We will get following result on execution of descend query
‘Thus due to change in ordering of the ules we get different results
dar changes the solutions
Goal or
change the ordering ofthe goals by keeping the ordering of the rules as
jon of the above program by changing the order of gos!
step 3: Now just
itis. W
family3Pl
fe will create another VersiFunctional and Logie Programming Langu,
ves of Programming Languages _§- 30 _Funeton
[Facts
childtuv ram)
chuldtram dasheat).
childidashrath,sia)
chliaja.rapbu,
‘We will get following result on execution of descend query
‘ip cine pocutr: escant? OHM os 9
You will get an error message (‘out of local stack’, or something similar). Prolog is
Iooping. Why? Well, in order to satisfy the query descend(uv/X) Prolog uses the frst rule
This means that its next goal will be to satisfy the query,
descend(luvX1)
For some new variable X1 . But to satisfy this new goal, Prolog again has to use the
first rule, and this means that its next goal is going to be,
descend (Iuv.X2)
For some new variable X2. And
to be descend(juv,X3) and then descend(Iuv,X4) and so on. Thus change in the goal order
has resulted in procedtural disaster.
of course, this in turn means that its next goal is going
Standard Terminology
‘The standard terminology is that in a rule the leftmost item of the body must be
identical with the rule's head.
Step 4: To overcome the above error causing situation just change the rule ordering
follows -
/Rules*/
descend(X¥)~ child),
easend(XY)~ descend(2,¥)chilA(X2),
/rFects*/
chalga ran)
sbuidram.dasbrath)Frneiles of Programming
child dashrath
=, —S=31__Funetona and Logie Programming Languages.
chlltaia agi). a
Now the output will be
Lists, Operators and Arithmetic
ists
* A list is an ordered sequence of objects and lists. In Prolog, a list is written as ts
elements separated by commas and enclosed in brackets. For example
11 & represents empty ist
label.
‘* In Prolog list elements are enclosed by brackets and separated by commas
234)
[Operator
Predicate calculus is a fundamental notation for representing and reasoning with
logical statements. t extends propositional calculus by introducing the quantifiers and Py
allowing predicates and functions of any number of variables.
4) Propositional symbols :P, QR, 5, T, .. denote propositions, or statements about
the world that maybe either true or false, such as “Sun is bright” or “India is a
country”.
2) Truth symbols : true, false.
3) Connectives : A (and), V (08), ~ (not), =.=
4) Propositional calculus sentences : Every propositional symbol and truth symbol
isa sentence.
For example The negation of a sentence is a sentence. Denoted as ~ P
are a sentence.
Any tsvo sentences connected by ane of [A V.=
For instance PV-Q=R,cf
a Lgl Pree Lara,
Pins of Pepramming Languages 5.32 S
a) ory ere ie or
conjuncts
InP VQ, P and Q are called disjunct
6) Symbols : The symbols ( ) and { ] are
and so control thir order of evaluation and meanin
Pv(-Q=R)are different,
nto sub-expressin
used to group symbols i ae
(Py ~Q)= Rand
‘Arithmetic
“The operator «is used for unification in Prolog, Following example iustrates the ure
of = for binding with the corresponding valve
In above code, variable A is bound to 10 + 20
‘The infix operator is evaluates the expression hence we get A = 30 for the second query
statement.
In the third query statement, 10 + 20 does not unify with 30. Hence we get false as 2
result of third query.
List Structure
A list is an ordered sequence of objects and lists. In prolog, a list is written as is
‘elements separated by commas and enclosed in brackets. For example
1] + represents empty et
lane ll
The list contains Head and Tail part. For example -If we type following query
2 Hm) = 110,20,30-401
We will get
H=10,
T = (20, 30,40).fe fe tn
3-labebixy
3rlabervziy
Now if we execute
Pe laibiol = faltolietnn.
‘Then we will get -
true
EEE consite town
hed(CH | TI, HD. cee
tnil(CH | TI, 7).
ist(QH | TI, H, D.
‘What will be
D hendd), X).
ii) list), X, 0.
iti) head{({a, b,c, dl, X).
in) tail fal, 0.
) Hist(a, bl, X.Y.
Solution
i) No
‘The fact for head returns ‘the
‘The empty list has neither hea¢
head of the list and we have passed an empty list.
.d, nor tail hence we get the answer as no or false.
ii) No
‘The fact for list returns head in X and til in Y. With the empey list we will get no
head and no tail: Hence isthe answer.
iii) X=a
“The fact for head returns h
get the answer a.
TECHNICAL PUBLICATIONS® - an up-trust for knowledge
ead of the list. As ais the head for the listfab.cd], weSeal ordering and rule on
Givw the exampte explaining hove
Explain the basic e
Explain list manipulation in protog
tering
coal tering changes the solution i proieg.
Comparison between Functional Programming and Logical Programming
and Object Oriented Programming Languages
1. Funetional Programming Vs. Logical Programming
Logical programming
Logical programming uses predicates,
Predicate cannot return a value. The predicate
In logic programming, a variable does not
Sr.No. Functional programming
1. Functional programming uses functions.
2 The functions can return a value
can be true or fase,
3. In functional programming, the variable
denotes the concrete value. need to refer to concrete value
4
Functional programming is normally used
for modelling reasoning
%
Examples - ML, HASKELL are fu
Programming languages
Logical programming is normally used for
‘modelling knowledge.
unctional Example - PROLOG isa logical programming
language.
2. OOP Vs. Logical Programming Vs. Functional Programming
sr.
No.
Object oriented
programming
Its based on objects and classes,
It is mainly used for enterprise
level applications,
cecution is by means.
Program
of exchange of message
between abject
Logical programming
tis based on predicates
Itis used for modelling
knowledge.
Program execution is by
‘means of proving the logic.
Functional programming
Itis based on evaluation of
functions.
Itis mainly used for
mathematical computations
Program execution is by
means of evaluation of
functionsMOOS of Frogran
‘i ZAIN Langapes
wl result is ——Firconat and Lope Programming Lanquopes
denoted by state
. Final results denoted by Fi
result i denoted
Examples -jova, Co ale of the main mucin
SI
2 eet diffrence tesa Ftonal eg 7
ce eee orang and ogc programming lang
el programming with logic and fnctional programing lang
EB uti
Definition ;
an : Popaming paradigm can be defined as a method of problem solving
© programming language design, __}
Various types of programming paradigm are
1. Imperative or procedural programming
2. Object oriented programming
3. Functional programming
Examples Prolog
ples - Prog Example LISP, ML. Haskell
aradigm Languages
4, Logic programming.
Examples of various programming languages based on the above mentioned
paradigm is as shown by following table
Imperative Object. «Functional Logie
piamnming —ofinted programming programming
ALGOL smaliaik USP Prolog
coBot Simla Haskell
ADA oo art
c jaa
PAScat
FORTRAN
et us discuss them in bret
Programming
impetrate means to comman
jented language.
also called as procedural programming lans¥28*
ERD imperative
The Latin word
ferent ori
1d, Hence this language is command
stat
driven _
myperativ® PCB!
Then
mming isFriehles rPranming Languages _5-a¢ Funan Le PET Lap
jon of each statement
‘A Program consists of sequence of statements. After executi f teMENt the
‘alae arestore inthe meme
The central features of this language are a aS
Fortan an soo
Examples of imperative programming are -C, Pascal, Ada,
Merit
1, Simple to implement.
2. These languages have low memory wtilibzation.
Demerits :
1. Large complex problems can not be implemented using this category of language
2. Parallel programming is not possible in this language.
3. This language is less productive and at low level compared to other programming
languages.
F] Object Oriental Programming
In this language everything is modeled as object. Hence is the name.
This language has a modular programming approach in which data and functions are
bound in one entity called class.
This programming paradigm has gained a great popularity in recent years because of
its characteristic features such as data abstraction, encapsulation, inheritance,
polymorphism and so on.
Examples of object oriented programming languages are - Smalltalk, C+, Java.
Merits :
1. It provides a modular programming approach,
2. It provides abstract data type in which some of the implementation details can be
hidden and protected.
Modifying the code for maintenance become easy, due to modules in the program
Modification in one module can not disturb the rest of the code.
4. Finding bugs become easy.
Object oriented programming provides good framework for code library fro
which the software components can be easily used and modified by the
programmer
oS _218 of Programmi
2
Coen n eamautees 5-27 santana Loi orang Languages.
1 Sometimes reat w,
implement. y. Hence it is complex to
‘orld objects can not be realized easi
Some of the mem
Not be ace bers(data or methods) of the class are hidden. Hence they can
Ie oben aan PY Beat oF ther cas
object orient
modules jean Prostamming everything ig arranged in the form of classes and
For the lower level applications i is not desirable feature.
EEE Functional Programming
In this parac
Fane adism the computations are expressed inthe frm of anions
a ‘onal programming paradigms treat values as single entities. Unlike variables,
es are never modified. Instead, values are transforme¢
fang Pistons of functional languages are performed largely through applying
tions to values ie, (+ 1020), This expression is interpreted as 10 + 20, The result 30
will be returned.
For building more complex functions the previously developed functions are used.
Thus program development proceeds by developing simple function development to
complex function development,
Examples of function programming are LISP, Haskell, ML
to new values.
Merits :
1. Due to use of functions the programs are easy to understand.
2. The functions are reusable.
3. It is possible to develop and maintain large programs consisting of large number
of functions.
Demerits :
1, Functional programming is less efficient than the other languages.
2, They consume large amount of time and memory for execution.
Purely functional programming is not a good option for commercial software
development.
Logie Programming
In this paradigm we express computation in terms of mathematical logic only. tis also
i= ( - )
| ( )
||
|
2 Explain the term Lambda abstraction
| ans: The lambda abstractions away of defining a new functions. The
/ (a )
2 SS(+ 1)) @) is a nameless
abstra,
fraction. The function is eval
function in which x is a variable and (x+1) is lambda
luated by substituting 3 for the variable x.
‘and bound variable?
23 What do you mean byte
Ans. : In 2 cal -
aleulus, a
tec ll the names are local to definitions. In the function Ax - x we say
und since ts accurence inthe body ofthe dito s preceded by 2. A
ed by Ais called free variable. For example
name not
(xe xy)
The vari
‘able x is bound variable whereas y is a free variable. The same variable can
appear many time:
wp ‘any times in the different context. Some instances of the variable may be
ound whereas other are free.
For example - In the expression
yy) Ax xy)
The variable y in the body of first expression from the left is bound to the frst 4, Hence
¥ is said to bound in first expression. Whereas variable x is bound to second lambda in
the second expres
ion but y is free. Hence in the second expression x is said to be
bound variable while y is said to be free variable.
Q.4 What is beta conversion?
‘Ans. : The basic operation in lambda calculus is the application of expression. For
example (2(x + 1))@) is equal to (3 + 1). Thus we are substituting the value 3 for the
variable x and throwing the lambda away. This is called beta conversion.
‘Thus beta conversion is a process of simplifying the expression and this removing the
lambdas.
5. Enlist the features of functional programming?
‘Ans.
1. The functional programming languages are modelled on the concept of
‘mathematical functions and make use of only conditional expressions and
recursion for the computational purpose.
‘The programs are constructed by building functional applications, That means
the values produced by one or more functions become the parameters to another
functions.
5, The purest form of functional programming languages use neither variables nor
statements, although this is relaxed somewhat in most applied
assignmening?
‘Applications of functional prograrnmna
The main domain of functional programming IaNBUABS . ee —
ain domain of functional prog owledge representa
This Tanguage is used fr building exper SYNE ine speech and ae ™
‘machine learning, natural language processing ™ i
al software.
Functional language is aso used for building mathematic
he function deft mpl
7 Explain the function definition in Scheme with sultale examPl® ;
. less function called lambda function. We
de
In scheme we can define a namel
Ne user defined function using define. The syntax is
|[Sene tunction_oame parameters)
(expression)
»
For example
We can define the function named add as follows -
|>(detine (ade num’ mum2}
(+ mumt num2)
H
Now, we can call the above function with two parameters for performing addition of
two numbers
> (add 19 20)
30
1.8 What Is car, edr and cons ?
‘Ans. : The car returns first element of a non empty list.
For example -
> (car(1234))
1
+ The cdr returns rest of the list after the first element is removed. Itis pronounced 2
could-er.
> (edr'(1 234)
(2.3.4)
* We can combine two lists using cons. The cons function takes two arguments a
returns a new cons cell containing the two values,
> (cons 10 (20 30 40))
(10 20 30 40)Prneles of yore
Programming Languages 5-41 umetonal end Logis PrOarMMund =
Q.9 Wha
Is Null predicate function in Scheme?
Ans. : This
Predicate is used
> (au? 41020 Sa
ie 30)
> (nun?)
le
check if it is empty list oF not.
If the isa li
argument is a list then it returns #t otherwise it returns éf.
2.10 Give the features of ML programming langu
Ans.
* MLisa static scoped functional programming language.
* The syntax of ML programming language is more like imperative programming
language.
* Everything is built from expressions.
© It provides for structured values such as lists, tuples and so on.
Q.11 How to use functions in ML?
Ans. : The function can be defined in ML using following syntax
ltun function name(formal parameters) = function body:
For example
leur cube(xint) = x"
Q.12 Describe the logic programming language lke Prolog.
%
Ans.
1)
Prolog is used in artificial intelligence and expert system ‘0 solve comple
problems.
2) Ieis used on pattern matching algorithm.
3) Tris used to develop systems based on object oriented concepts.
1d to build decision support systems that aid organizations
4) Prolog is uset
Je - Decision systems for medical diagnoses.
decision-making, For examp!
.13 State any four distinguishing features of functional and logical programming languages
(Refer section 5.7)
cers)Principles Functional and Logic Programing Language
of Programming Languages ___5- 42 _Funct a
14 What is programming paradigm 7 |
Ans. : Programming paradigm can be defined as a method of problem solving and an
approach to programming language design.
Various types of programming paradigm are -
1. Imperative or procedural programming
2. Object oriented programming
3. Functional programming
4. Logic programming.
aqua