Reputation: 29084
I have been too used to Imperative Programming which is the usual way of telling the computer to perform step by step the procedure to get the final result. On the other hand, declarative programming just passes the input and expects the output without stating the procedure of how it is done. The one I am confused about is Functional Programming. I know Functional Programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data and is not a type of declarative language. However, I cannot still comprehend how it can work.
Let's take an example of executing the Fibonacci numbers.
Imperative Programming:
#include<stdio.h>
#include<conio.h>
main()
{
int n,i,c,a=0,b=1;
printf("Enter Fibonacci series of nth term : ");
scanf("%d",&n);
printf("%d %d ",a,b);
for(i=0;i<=(n-3);i++)
{
c=a+b;
a=b;
b=c;
}
printf("%d ",c);
getch();
}
Declarative Programming:
Give the nth number and it will return the value of the nth number
How does the Functional Program work?
Plus do correct me if my definitions are wrong. Please feel free to comment..
Upvotes: 69
Views: 42089
Reputation: 1162
The idea that there are declarative languages and then there are imperative languages is a myth.
Every single thing you do in (say) Java is a declaration of intent to the compiler as to what you need the byte code to achieve. You don't care how it is achieved. But the byte code itself is a declaration of intent to the JIT compiler of what you want the machine instructions to achieve. You don't care how it is achieved.
Not even assembly is truly imperative. The CPU interprets the machine code and performs all manner of optimisations and transformations to it. And (other than wanting it to be very fast) the guy who wrote the assembly (do people still write assembly?) doesn't care that AMD cores and IBM cores will execute the machine instructions in different ways.
In the other direction, every call to a library function is a declaration of intent to the library writer as to what you want the call to achieve, but you don't (typically) care how it is achieved. And in turn your code itself may be used to satisfy other people's declarations of intent, without them caring how you did it.
Conversely, simple SQL statements are unable to satisfy complex requirements (unsurprisingly). In order to get what one wants, you have to use either lots of nested sub-selects (if you're a masochist) or write interim results to temporary tables and apply further sets of queries to it, each of which may require more queries on more temporary tables (if you're a pragmatist). The two approaches are equivalent. And which ever one you take, it represents an "imperative" series of instructions.
Really all declarative means is "very high level". But to get what you actually need, you have to frequently drop to a lower level. Similarly a Java API may itself emulate a so-called declarative language (database.select().from(table1, table2).where(<lambda>).groupBy(<lambda>)).having(<lambda>)
). But when it's written like that, it doesn't look so "declarative" any more, does it? It looks an awful lot like you're chaining imperative instructions together.
That example demonstrates the way that Java can be used as a so-called functional language. So is SQL functional? The Java version looks almost the same, and does the same thing. But it's written in an "imperative" language. So is SQL imperative? Is Java functional? Declarative?
Language developers and language advocates love to present their languages as having certain qualities which make them sound fundamentally different from mainstream languages, as having a distinct philosophical approach to problem solving. But generally a few scratches to the surface reveal something more workaday.
I wouldn't get bogged down in what imperative, functional and declarative mean. Every language is declarative, and imperative, and functional. Find the style of writing code which suits your taste, and use the language(s) which suit(s) your style.
Upvotes: 2
Reputation: 49361
In functional programming we build immutable programs by using pure functions. This what pure functions are: (I mention about pure functions because functional programming is based on pure functions)
with the short description of pure functions, functional programming refers to the declarative evaluation of pure functions to create immutable programs by avoiding externally observable side effects.
Simply speaking, functional programming is declarative programming paradigms which is a paradigm that expresses a set of operations without revealing how they’re implemented or how data flows through them. Imperative programming treats a computer program as merely a sequence of top-to-bottom statements that changes the state of the system in order to compute a result.
Here is an example of imperative programming: We loop over an array, we calculate the square of each element, and we store the new values inside the same array. We are mutating the array. Also, this loop is not reusable, for each different array, we would define a new for-loop.
var array= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for(let i= 0; i < array.length; i++) {
array[i]=Math.pow(array[i], 2);
}
array; //-> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In javascript I would use Array.map()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((i)=>i*i)
In this method, we do not know how Array.map() is implemented. Definition of program is separated from the evaluation. More importantly, this code does not mutate the original array, it creates a new array
Another good example of declarative programming is writing SQL queries. We just write a simple SQL statement to pull the data from database, but we do not know what is happening behind the scene, all the magic is abstracted away from us.
Upvotes: 4
Reputation: 18811
Your example of declarative programming above is not an actual program, so it's not a good example.
The main difference is between imperative and declarative. Functional is a particular kind of declarative.
C, C++, Java, Javascript, BASIC, Python, Ruby, and most other programming languages are imperative. As a rule, if it has explicit loops (for, while, repeat) that change variables with explicit assignment operations at each loop, then it's imperative.
SQL and XSLT are two well-known examples of declarative programming. Markup languages such as HTML and CSS are declarative too, although they are usually not powerful enough to describe arbitrary algorithms.
Here is an example computation (summing the income by gender, from a suitable data source) first written in an imperative language (Javascript) and then in a declarative language (SQL).
var income_m = 0, income_f = 0;
for (var i = 0; i < income_list.length; i++) {
if (income_list[i].gender == 'M')
income_m += income_list[i].income;
else
income_f += income_list[i].income;
}
Notice:
i
) and the running totals at each iteration;if
s) are only used to choose the code path at each iteration.select gender, sum(income)
from income_list
group by gender;
Notice:
case
in SQL) are used in a functional way to specify the output value you want based on the input values, not to choose a code path.As I mentioned above, SQL's case
is a great example of the functional way of programming, which is a restricted subset of Declarative programming in which the desired computation is specified by composing functions.
Functions are things that accept inputs and return outputs (eg. case
, sum()
…)
Composition means chaining two or more together by specifying how the output of one is fed as the input to the next (typically by writing one inside the other.) Finally the whole composition, which is still itself a big function, is applied to the available inputs to get the desired output.
In this snippet I am declaring the output I want by composing the functions sum()
and case
. This is called functional programming:
select
sum(case when some_flag = 'X' then some_column
else some_other_column end)
from
...
If the composition of two or more functions and their application to the input data are the only constructs available in a given language, that language is said to be purely functional. In those languages you will notice the complete absence of loops, variable assignment and other typically imperative statements.
Edit: I recommend watching some of Anjana Vakil's talks on functional programming in Javascript, to get a better idea of what it's about.
Upvotes: 136
Reputation: 4245
Another useful explanation I found in the Pro XAML with C#:
In declarative programming, the source code is written in a way that expresses the desired outcome of the code with little or no emphasis on the actual implementation.
Imperative programming is the opposite of declarative programming. If declarative programming can be thought of as declaring what the desired outcome is, imperative programming can be viewed as writing lines of code that represent the instructions of how to achieve the desired outcome.
Upvotes: 6
Reputation: 6131
It is an erroneous oversimplification to claim that imperative programming is distinguished from declarative programming by erroneously assuming a lack of ordering in the latter.
Pure functional programming is not prevented from expressing order and implementation, rather it is less able to express random accidental order at the operational semantics level. Also it has the advantage of "Don't repeat yourself" (DRY), which is a form of declarative style (see below).
However, pure functional programming does not guarantee declarative high-level semantics. For this, you need to apply the correct definition of declarative vs. imperative.
Upvotes: 7
Reputation: 840
Think of c filters. Where you read from stdin and write to stdout. The code may be imperative but thr program is used like a a function. Say you have a program 'function, then piping to it:
cat foo |function |tee bar
Will filter the contents of foo through function then through the filter tee to both write to stdout and create bar . Think also of grep and awk the iterator in both is implied and they are used like functions.
Upvotes: 1