Unit-5 1
Unit-5 1
Unit-5 1
1. Haskell:
2. Haskell is a purely functional programming language known for its strong static
typing system and lazy evaluation.
3. It has a rich type system and powerful features for writing concise and expressive
code.
4. Scala:
5. Scala is a hybrid functional programming language that runs on the Java Virtual
Machine (JVM).
6. It combines functional programming features with object-oriented programming,
making it suitable for both paradigms.
7. Clojure: Clojure is a functional programming language that runs on the Java Virtual
Machine and is designed for concurrency and interoperability with Java.
8. It emphasizes immutable data structures and provides powerful features for
managing state in concurrent programs.
9. Erlang:
Erlang is a functional programming language designed for building fault-tolerant
and highly available distributed systems.
It supports lightweight concurrency through its actor-based model and has built-in
support for message passing between concurrent processes.
1. Conciseness(short):
2. Functional programming languages often allow developers to express complex ideas
in fewer lines of code compared to imperative languages.
3. Safety:
4. Immutable data and pure functions make it easier to reason about the behavior of
programs and reduce the likelihood of bugs related to side effects and mutable
state.
5. Concurrency:
6. Functional programming languages often provide built-in support for concurrency
and parallelism, making it easier to write scalable and high-performance applications.
7. Expressiveness:
8. Functional programming languages provide powerful abstractions for working with
data and expressing algorithms, making it easier to write expressive and declarative
code.
Mathematical Functions:
1. Determinism:
2. A function always produces the same output for a given input.
3. Referential Transparency:
4. The output of a function depends only on its input, and it does not have any side
effects.
5. Immutability:
6. The function does not modify the input or any external state.
7. Pureness:
8. A pure function is free from side effects and has referential transparency.
1. First-Class Functions:
2. Functions are treated as first-class citizens, meaning they can be passed as
arguments to other functions, returned as values from other functions, and assigned
to variables.
3. Higher-Order Functions:
4. Higher-order functions take other functions as arguments or return them as results.
They enable powerful abstractions and allow for the composition of functions.
5. Immutable Data:
6. Functional programming languages encourage immutability, where once a value is
assigned, it cannot be changed. Immutable data structures are preferred, which helps
in writing pure functions and avoiding side effects.
7. Pure Functions:
8. Pure functions are the cornerstone of functional programming. They always produce
the same output for a given input and have no side effects. Pure functions are
deterministic and referentially transparent.
9. Recursion:
Recursion is often favored over iteration in functional programming languages. It
allows for concise and elegant solutions to many problems, especially those related
to traversing and manipulating data structures.
Lazy Evaluation:
Some functional programming languages support lazy evaluation, where expressions
are not evaluated until their results are needed. Lazy evaluation can improve
performance and enable more efficient use of resources.
Benefits of Mathematical Functions in Functional Programming
Languages:
An anonymous function is defined in JavaScript with the same syntax, except that the name
of the function is omitted.
C# supports lambda expressions that have a different syntax than that of C# functions.
For example, we could have the following:
i => (i % 2) == 0
This lambda expression returns a Boolean value depending on whether the given parameter (i) is even
(true) or odd (false). C#’s lambda expressions can have more than one parameter and more than
one statement.
Python’s lambda expressions define simple one-statement anonymous functions that can
have more than one parameter. The syntax of a lambda expression in Python is exemplified
by the following:
lambda a, b : 2 * a – b
Note that the formal parameters are separated from function body by a colon. Python includes the
higher-order functions filter and map. Both often use lambda expressions as their first parameter.
The second parameter of these
is a sequence type, and both return the same sequence type as their second parameter. In Python,
strings, lists, and tuples are considered sequences. Consider the following example of using the map
function in Python:
The from declaration here imports the functional version of the addition operator, which is
named add, from the operator module.
After defining add5, it can be used with one parameter, as in the following:
add5(15)
x = times.(3, 4)
This sets x to 12. The times object can be curried with the following:
times5 = times.curry.(5)
x5 = times5.(3)
Functional languages can have a very simple syntactic structure. The list structure of LISP,
which is used for both code and data, clearly illustrates this.
The semantics of functional languages is also simpler than that of the imperative languages.
For example, in the de notational semantics description of an imperative loop construct given
in the loop is converted from an iterative construct to a recursive construct. This conversion is
unnecessary in a pure functional language, in which there is no iteration. Furthermore, we
assumed there were no expression side effects in all of the denotational semantic
descriptions of imperative constructs
This restriction is unrealistic, because all of the C-based languages include expression side
effects. This restriction is not needed for the denotational descriptions of pure functional
languages.
Some in the functional programming community have claimed that the use of functional programming
results in an order-of-magnitude increase in productivity, largely due to functional programs being
claimed to be only 10 percent as large as their imperative counterparts. While such numbers have been
actually shown for certain problem areas, for other problem areas, functional programs are more like 25
percent as large as imperative solutions to the same problems (Wadler, 1998). These factors allow
proponents of functional programming to claim productivity advantages over imperative programming of
4 to 10 times. However, program size alone is not necessarily a good measure of productivity. Certainly
not all lines of source code have equal complexity,
programming Paradigm:
Imperative Languages: Imperative languages focus on describing the
steps that a program should take to reach a certain goal.
They rely heavily on statements that change the program's state
through assignment and control flow structures like loops and
conditionals.
Functional Languages: Functional languages, on the other hand, treat
computation as the evaluation of mathematical functions and
emphasize immutable data and expression evaluation rather than
changing state. They discourage or eliminate side effects and mutable
state.
State Management:
Imperative Languages: In imperative languages, managing state is a
core concept. Variables are mutable, and the program's behavior often
depends on the current state.
Functional Languages: Functional languages emphasize immutability,
meaning once a value is assigned, it cannot be changed. Instead of
mutating data, functional programming prefers creating new data
structures through transformations.
Control Flow:
Imperative Languages: Control flow structures like loops and
conditionals are fundamental to imperative languages. Programs are
typically structured around changing state based on certain conditions.
Functional Languages: Functional programming often uses higher-
order functions like map, reduce, and filter for control flow. Recursion is
also common for iteration.
Side Effects:
Imperative Languages: Imperative languages commonly allow side
effects, which are changes to state or behavior that occur outside the
primary function or method being executed.
Functional Languages: Functional languages aim to minimize or
eliminate side effects, promoting pure functions that only depend on
their input and produce consistent output without modifying external
state.
Concurrency and Parallelism:
Imperative Languages: Concurrency and parallelism in imperative
languages can be complex due to mutable state and shared memory.
Synchronization mechanisms like locks and semaphores are often used.
Functional Languages: Functional languages inherently support
concurrency and parallelism due to their emphasis on immutability and
pure functions. This makes concurrent programming safer and more
manageable.
Expressiveness and Readability:
Imperative Languages: Imperative languages are often more verbose,
as they explicitly describe the steps needed to achieve a particular
outcome.
Functional Languages: Functional languages tend to be more concise
and expressive, as they focus on what needs to be done rather than
how to do it.
Typing Systems:
Imperative Languages: Imperative languages may use static or
dynamic typing systems,
where variables are explicitly declared or inferred at runtime,
respectively.
Functional Languages: Functional languages often use static typing
systems, which can help catch errors at compile time and provide
better tooling support for refactoring and maintaining code.
A is called the head of the rule, B1 , ..., Bn is called the body, and the Bi are
called literals or conditions. When n = 0, the rule is called a fact and is written in the
simplified form:
A.
Queries (or goals) have the same syntax as the bodies of rules and are commonly written
in the form:
?- B1, ..., Bn.
In the simplest case of Horn clauses (or "definite" clauses), all of the A, B1, ...,
Bn are atomic formulae of the form p(t1 ,..., tm), where p is a predicate symbol naming a
relation, like "motherhood", and the ti are terms naming objects (or individuals). Terms
include both constant symbols, like "charles", and variables, such as X, which start with
an upper case letter.
Consider, for example, the following Horn clause program:
mother_child(elizabeth, charles).
father_child(charles, william).
father_child(charles, harry).
parent_child(X, Y) :-
mother_child(X, Y).
parent_child(X, Y) :-
father_child(X, Y).
grandparent_child(X, Y) :-
parent_child(X, Z),
parent_child(Z, Y).
Given a query, the program produces answers. For instance for a query ?-
parent_child(X, william) , the single answer is
X = charles
Various queries can be asked. For instance the program can be queried both to generate
grandparents and to generate grandchildren. It can even be used to generate all pairs of
grandchildren and grandparents, or simply to check if a given pair is such a pair:
grandparent_child(X, william).
X = elizabeth
?- grandparent_child(elizabeth, Y).
Y = william;
Y = harry.
?- grandparent_child(X, Y).
X = elizabeth
Y = william;
X = elizabeth
Y = harry.
?- grandparent_child(william, harry).
no
?- grandparent_child(elizabeth, harry).
yes
Although Horn clause logic programs are Turing complete,[1][2] for most practical
applications, Horn clause programs need to be extended to "normal" logic programs with
negative conditions. For example, the definition of sibling uses a negative condition,
where the predicate = is defined by the clause X = X:
sibling(X, Y) :-
parent_child(Z, X),
parent_child(Z, Y),
not(X = Y).
Logic programming languages that include negative conditions have the knowledge
representation capabilities of a non-monotonic logic.
In ASP and Datalog, logic programs have only a declarative reading, and their execution
is performed by means of a proof procedure or model generator whose behaviour is not
meant to be controlled by the programmer. However, in the Prolog family of languages,
logic programs also have a procedural interpretation as goal-reduction procedures. From
this point of view, clause A :- B1,...,Bn is understood as:
to solve A , solve B1 , and ... and solve Bn .
Negative conditions in the bodies of clauses also have a procedural interpretation, known
as negation as failure: A negative literal not B is deemed to hold if and only if the
positive literal B fails to hold.
Much of the research in the field of logic programming has been concerned with trying to
develop a logical semantics for negation as failure and with developing other semantics
and other implementations for negation. These developments have been important, in
turn, for supporting the development of formal methods for logic-based program
verification and program transformation.
A variable is any string of letters, digits, and underscores that begins with an
uppercase letter or an underscore (_).
Instantiations last only as long as it takes to satisfy one complete goal, which
involves the proof or disproof of one proposition.
Prolog variables are only distant relatives, in terms of both semantics and use, to the
variables in the imperative languages. The last kind of term is called a structure.
Structures represent the atomic propositions of predicate calculus, and their general
form is the same:
The functor is any atom and is used to identify the structure. The parameter list can
be any list of atoms, variables, or other structures. As discussed at length in the
following subsection, structures are the means of specifying facts in Prolog. They
can also be thought of as objects, in which case they allow facts to be stated in
terms of several related atoms. In this sense, structures are relations, for they state
relationships among terms. A structure is also a predicate when its context specifies
it to be a query.
Fact Statements
Prolog has two basic statement forms; these correspond to the headless and headed
Horn clauses of predicate calculus.
The simplest form of headless Horn clause in Prolog is a single structure, which is
interpreted as an unconditional assertion, or fact. Logically, facts are simply
propositions that are assumed to be true.
The following examples illustrate the kinds of facts one can have in a Prolog
program. Notice that every Prolog statement is terminated by a period.
These simple structures state certain facts about jake, shelley, bill, and mary.
The last four connect their two parameters with a relationship that is named in the
functor atom; for example, the fifth proposition might be interpreted to mean that bill
is the father of jake.
Note that these Prolog propositions, like those of predicate calculus, have no intrinsic
semantics.
They mean whatever the programmer wants them to mean. For example, the
proposition
could mean bill and jake have the same father or that jake is the father of bill.
The most common and straightforward meaning, however, might be that bill is the
father of jake.
Rule Statements
The other basic form of Prolog statement for constructing the database corresponds
to a headed Horn clause.
The right side is the antecedent, or if part, and the left side is the
consequent, or then part. If the antecedent of a Prolog statement is true, then the
consequent of the statement must also be true. Because they are Horn clauses, the
consequent of a Prolog statement is a single term, while the antecedent can be
Conjunctions contain multiple terms that are separated by logical AND operations. In
Prolog, the AND operation is implied. The structures that specify atomic propositions
in a conjunction are separated by commas, so one could consider the commas to be
AND operators. As an example of a conjunction, consider the following:
consequence: - antecedent_expression.
states that if mary is the mother of shelley, then mary is an ancestor of shelley.
Headed Horn clauses are called rules, because they state rules of implication
between propositions.
1. Facts:
In Prolog, facts are statements about the world that are assumed to be
true. Facts consist of predicates and arguments. Predicates represent
relationships or properties, and arguments provide the specific details.
For example:
parent(sanjay, maya).
2. Rules:
Rules in Prolog define relationships or conditions based on other facts or
rules.
They are used to derive new information or make logical inferences. Rules
consist of a head (the conclusion) and a body (the condition). The head
specifies the result or conclusion, while the body contains the conditions or
requirements for the rule to be true.
For example:
3. Queries:
In Prolog, you can ask queries to the system to retrieve information or test
relationships. Queries are entered in the form of goals, which are logical
statements that you want to prove or find solutions for. You can ask queries
using the syntax:
?- goal.
For example:
?- ancestor(sanjay, maya).
4. Variables:
Variables are used in Prolog to represent unknown values or placeholders.
They start with an uppercase letter or an underscore (_) and can be used
to instantiate values during the execution of a query or rule. Variables allow
Prolog to find solutions and perform unification, which is the process of
matching values. For example:
?- parent(X, maya).
Here, X is a variable, and Prolog will attempt to find a value for X that
satisfies the query.
5. Logical Operators:
Prolog provides logical operators to combine conditions and goals.
2. Computational Linguistics:
Logic programming is widely used in natural language processing (NLP)
tasks. It provides a formal and logical framework for representing grammar
rules, parsing sentences, semantic analysis, machine translation,
information extraction, and question answering systems.
3. Expert Systems:
Logic programming has been used in the development of expert systems,
which are computer-based systems that mimic human expertise in a
specific domain. Prolog’s ability to represent knowledge in rules and facts
makes it suitable for implementing expert systems that can perform
complex reasoning and decision-making tasks.
4. Database Querying:
Logic programming languages, including Prolog, can be used for querying
databases. The logical querying capabilities allow for expressing complex
queries involving multiple relationships and conditions. Prolog’s ability to
perform pattern matching and unification makes it useful for retrieving
information from relational databases.
5. Constraint Solving:
Logic programming is effective in solving constraint satisfaction problems
(CSPs). CSPs involve finding solutions that satisfy a set of constraints or
conditions. Prolog’s ability to handle logical constraints and perform
backtracking search makes it well-suited for solving puzzles, scheduling
problems, and optimization tasks.
8. Semantic Web:
Logic programming languages are utilized in the Semantic Web domain to
represent and reason with knowledge on the web. They provide a formal
framework for representing ontologies, semantic rules,
41. Conclusions Advantages: • Prolog programs based on logic, so likely to be more logically
organized and written • Processing is naturally parallel, so Prolog interpreters can take
advantage of multi-processor machines • Programs are concise, so development time is
decreased – good for prototyping