What is difference between functional and imperative programming languages?

后端 未结 10 2126
庸人自扰
庸人自扰 2020-12-12 08:45

Most of the mainstream languages, including object-oriented programming (OOP) languages such as C#, Visual Basic, C++, and Java were designed to primarily support imperative

相关标签:
10条回答
  • 2020-12-12 09:19

    Functional programming is "programming with functions," where a function has some expected mathematical properties, including referential transparency. From these properties, further properties flow, in particular familiar reasoning steps enabled by substitutability that lead to mathematical proofs (i.e. justifying confidence in a result).

    It follows that a functional program is merely an expression.

    You can easily see the contrast between the two styles by noting the places in an imperative program where an expression is no longer referentially transparent (and therefore is not built with functions and values, and cannot itself be part of a function). The two most obvious places are: mutation (e.g. variables) other side-effects non-local control flow (e.g. exceptions)

    On this framework of programs-as-expressions which are composed of functions and values, is built an entire practical paradigm of languages, concepts, "functional patterns", combinators, and various type systems and evaluation algorithms.

    By the most extreme definition, almost any language—even C or Java—can be called functional, but usually people reserve the term for languages with specifically relevant abstractions (such as closures, immutable values, and syntactic aids like pattern matching). As far as use of functional programming is concerned it involves use of functins and builds code without any side effects . used to write proofs

    0 讨论(0)
  • 2020-12-12 09:26

    Here is the difference:

    Imperative:

    • Start
    • Turn on your shoes size 9 1/2.
    • Make room in your pocket to keep an array[7] of keys.
    • Put the keys in the room for the keys in the pocket.
    • Enter garage.
    • Open garage.
    • Enter Car.

    ... and so on and on ...

    • Put the milk in the refrigerator.
    • Stop.

    Declarative, whereof functional is a subcategory:

    • Milk is a healthy drink, unless you have problems digesting lactose.
    • Usually, one stores milk in a refrigerator.
    • A refrigerator is a box that keeps the things in it cool.
    • A store is a place where items are sold.
    • By "selling" we mean the exchange of things for money.
    • Also, the exchange of money for things is called "buying".

    ... and so on and on ...

    • Make sure we have milk in the refrigerator (when we need it - for lazy functional languages).

    Summary: In imperative languages you tell the computer how to change bits, bytes and words in it's memory and in what order. In functional ones, we tell the computer what things, actions etc. are. For example, we say that the factorial of 0 is 1, and the factorial of every other natural number is the product of that number and the factorial of its predecessor. We don't say: To compute the factorial of n, reserve a memory region and store 1 there, then multiply the number in that memory region with the numbers 2 to n and store the result at the same place, and at the end, the memory region will contain the factorial.

    0 讨论(0)
  • 2020-12-12 09:28
    //The IMPERATIVE way
    int a = ...
    int b = ...    
    
    int c = 0; //1. there is mutable data
    c = a+b;   //2. statements (our +, our =) are used to update existing data (variable c)
    

    An imperative program = sequence of statements that change existing data.

    Focus on WHAT = our mutating data (modifiable values aka variables).

    To chain imperative statements = use procedures (and/or oop).


    //The FUNCTIONAL way
    const int a = ... //data is always immutable
    const int b = ... //data is always immutable
    
    //1. declare pure functions; we use statements to create "new" data (the result of our +), but nothing is ever "changed"
    int add(x, y) 
    {
       return x+y;
    } 
    
    //2. usage = call functions to get new data
    const int c = add(a,b); //c can only be assigned (=) once (const)
    

    A functional program = a list of functions "explaining" how new data can be obtained.

    Focus on HOW = our function add.

    To chain functional "statements" = use function composition.


    These fundamental distinctions have deep implications.

    Serious software has a lot of data and a lot of code.

    So same data (variable) is used in multiple parts of the code.

    A. In an imperative program, the mutability of this (shared) data causes issues

    • code is hard to understand/maintain (since data can be modified in different locations/ways/moments)
    • parallelizing code is hard (only one thread can mutate a memory location at the time) which means mutating accesses to same variable have to be serialized.

    As an advantage: data is modified in place, less need to copy.

    B. On the other hand, functional code uses immutable data which does not have such issues. Data is readonly so there are no race conditions. Code can be easily parallelized. Results can be cached.

    As a disadvantage: data is copied a lot in order to get "modifications".

    0 讨论(0)
  • 2020-12-12 09:32

    Functional Programming is a form of declarative programming, which describe the logic of computation and the order of execution is completely de-emphasized.

    Problem: I want to change this creature from a horse to a giraffe.

    • Lengthen neck
    • Lengthen legs
    • Apply spots
    • Give the creature a black tongue
    • Remove horse tail

    Each item can be run in any order to produce the same result.

    Imperative Programming is procedural. State and order is important.

    Problem: I want to park my car.

    1. Note the initial state of the garage door
    2. Stop car in driveway
    3. If the garage door is closed, open garage door, remember new state; otherwise continue
    4. Pull car into garage
    5. Close garage door

    Each step must be done in order to arrive at desired result. Pulling into the garage while the garage door is closed would result in a broken garage door.

    0 讨论(0)
  • 2020-12-12 09:33

    Most modern languages are in varying degree both imperative and functional but to better understand functional programming, it will be best to take an example of pure functional language like Haskell in contrast of imperative code in not so functional language like java/C#. I believe it is always easy to explain by example, so below is one.

    Functional programming: calculate factorial of n i.e n! i.e n x (n-1) x (n-2) x ...x 2 X 1

    -- | Haskell comment goes like
    -- | below 2 lines is code to calculate factorial and 3rd is it's execution  
    
    factorial 0 = 1
    factorial n = n * factorial (n - 1)
    factorial 3
    
    -- | for brevity let's call factorial as f; And x => y shows order execution left to right
    -- | above executes as := f(3) as 3 x f(2) => f(2) as 2 x f(1) => f(1) as 1 x f(0) => f(0) as 1  
    -- | 3 x (2 x (1 x (1)) = 6
    

    Notice that Haskel allows function overloading to the level of argument value. Now below is example of imperative code in increasing degree of imperativeness:

    //somewhat functional way
    function factorial(n) {
      if(n < 1) {
         return 1;
      }
      return n * factorial(n-1);   
    }
    factorial(3);
    
    //somewhat more imperative way
    function imperativeFactor(n) {
      int f = 1;
      for(int i = 1; i <= n; i++) {
         f = f * i;
      }
      return f;
    }
    

    This read can be a good reference to understand that how imperative code focus more on how part, state of machine (i in for loop), order of execution, flow control.

    The later example can be seen as java/C# lang code roughly and first part as limitation of the language itself in contrast of Haskell to overload the function by value (zero) and hence can be said it is not purist functional language, on the other hand you can say it support functional prog. to some extent.

    Disclosure: none of the above code is tested/executed but hopefully should be good enough to convey the concept; also I would appreciate comments for any such correction :)

    0 讨论(0)
  • 2020-12-12 09:35

    I know this question is older and others already explained it well, I would like to give an example problem which explains the same in simple terms.

    Problem: Writing the 1's table.

    Solution: -

    By Imperative style: =>

        1*1=1
        1*2=2
        1*3=3
        .
        .
        .
        1*n=n 
    

    By Functional style: =>

        1
        2
        3
        .
        .
        .
        n
    

    Explanation in Imperative style we write the instructions more explicitly and which can be called as in more simplified manner.

    Where as in Functional style, things which are self-explanatory will be ignored.

    0 讨论(0)
提交回复
热议问题