How can you do anything useful without mutable state?

后端 未结 18 1804
栀梦
栀梦 2020-11-28 17:12

I\'ve been reading a lot of stuff about functional programming lately, and I can understand most of it, but the one thing I just can\'t wrap my head around is stateless codi

18条回答
  •  猫巷女王i
    2020-11-28 17:44

    Note that saying functional programming does not have 'state' is a little misleading and might be the cause of the confusion. It definitely has no 'mutable state', but it can still have values that are manipulated; they just cannot be changed in-place (e.g. you have to create new values from the old values).

    This is a gross over-simplification, but imagine you had an OO language, where all the properties on classes are set once only in the constructor, all methods are static functions. You could still perform pretty much any calculation by having methods take objects containing all the values they needs for their calculations and then returning new objects with the result (maybe a new instance of the same object even).

    It may be 'hard' to translate existing code into this paradigm, but that is because it really requires a completely different way of thinking about code. As a side-effect though in most cases you get a lot of opportunity for parallelism for free.

    Addendum: (Regarding your edit of how to keep track of values that need to change)
    They would be stored in an immutable data structure of course...

    This is not a suggested 'solution', but the easiest way to see that this will always work is that you could store these immutable values into a map (dictionary / hashtable) like structure, keyed by a 'variable name'.

    Obviously in practical solutions you'd use a more sane approach, but this does show that worst-case if nothing else'd work you could 'simulate' mutable state with such a map that you carry around through your invocation tree.

提交回复
热议问题