I would like understand the difference between functional, and declarative programming.
Can you show me an example where the code is declarative, but not yet functional?
Is it possible to be functional but not declarative, i.e. imperative?
Functional Programming is a declarative programming paradigm, in contrast to imperative programming paradigms. Declarative programming is a paradigm describing WHAT the program does, without explicitly specifying its control flow.
Procedural programming uses a very detailed list of instructions to tell the computer what to do step by step. This approach uses iteration to repeat a series of steps as often as needed. Functional programming is an approach to problem solving that treats every computation as a mathematical function.
Functional programming languages are declarative, meaning that a computation's logic is expressed without describing its control flow. In declarative programming, there are no statements. Instead, programmers use expressions to tell the computer what needs to be done, but not how to accomplish the task.
No. Functional programming is not per se the same as declarative programming and vice versa. Prolog - which is logical programming - is by many considered to be a declarative programming language as well.
A non-functional declarative language is PROLOG. Programming in PROLOG is stating a number of facts, and then ask questions, which the system tries to verify or deny.
Example:
human(socrates). // "Socrates is a human."
mortal(X) :- human(X). // "If X is a human, then X is mortal" or
// "All humans are mortal."
? mortal(socrates) // Is Socrates mortal?
Yes.
? mortal(X) // Who is mortal?
socrates
? mortal(pythagoras).
No. // since system doesn't know about any human except Socrates
Another well known language that is declarative, but not functional, is SQL.
Note that there are not only no functions as first class values. In the PROLOG example, there are no functions at all! To be sure, both SQL and PROLOG have some built-in functions, but have no way to let you write your own functions. One could think that the rule
mortal(X) :- human(X).
is a function, but it isn't, it is an inference rule. Hence, declarative, non-functional languages.
For the second part of your question: it is certainly possible to write imperative code in functional programming languages. Simon Peyton Jones once stated that he thinks that Haskell is the finest imperative programming language in the world. (And this was only a half joke.)
Example:
main = do
print "Enter a number"
line <- getLine
print (succ (read line :: Int))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With