What is difference between functional and imperative programming languages?

后端 未结 10 2138
庸人自扰
庸人自扰 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: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 :)

提交回复
热议问题