Does functional programming avoid state?

前端 未结 4 1700
死守一世寂寞
死守一世寂寞 2021-02-01 20:44

According to wikipedia: functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state an

相关标签:
4条回答
  • 2021-02-01 20:53

    I think you're just using the term "state" in an unusual way. If you consider adding 1 and 1 to get 2 as being stateful, then you could say functional programming embraces state. But when most people say "state," they mean storing and changing values, such that calling a function might leave things different than before the function was called, and calling the function a second time with the same input might not have the same result.

    Essentially, stateless computations are things like this:

    • The result of 1 + 1
    • The string consisting of 's' prepended to "pool"
    • The area of a given rectangle

    Stateful computations are things like this:

    • Increment a counter
    • Remove an element from the array
    • Set the width of a rectangle to be twice what it is now
    0 讨论(0)
  • 2021-02-01 20:53

    The Wikipedia definition is correct. It may seem puzzling at first, but if you start working with say Haskell, you'll note that you don't have any variables laying around containing values.

    State can still be sort of represented using state monads.

    0 讨论(0)
  • 2021-02-01 20:56

    Rather than avoids state, think of it like this:

    It avoids changing state. That word "mutable".

    Think in terms of a C# or Java object. Normally you would call a method on the object and you might expect it to modify its internal state as a result of that method call.

    With functional programming, you still have data, but it's just passed through each function, creating output that corresponds to the input and the operation.

    At least in theory. In reality, not everything you do actually works functionally so you frequently end up hiding state to make things work.

    Edit:
    Of course, hiding state also frequently leads to some spectacular bugs, which is why you should only use functional programming languages for purely functional situations. I've found that the best languages are the ones that are object oriented and functional, like Python or C#, giving you the best of both worlds and the freedom to move between each as necessary.

    0 讨论(0)
  • 2021-02-01 21:14

    The Wikipedia definition is right. Functional programming avoids state. Functional programming means that you apply a function to a given input and get a result. However, it is guaranteed that your input will not be modified in any way. It doesn't mean that you cannot have a state at all. Monads are perfect example of that.

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