How can you do anything useful without mutable state?

后端 未结 18 1754
栀梦
栀梦 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条回答
  •  遥遥无期
    2020-11-28 17:52

    Here's how you write code without mutable state: instead of putting changing state into mutable variables, you put it into the parameters of functions. And instead of writing loops, you write recursive functions. So for example this imperative code:

    f_imperative(y) {
      local x;
      x := e;
      while p(x, y) do
        x := g(x, y)
      return h(x, y)
    }
    

    becomes this functional code (Scheme-like syntax):

    (define (f-functional y) 
      (letrec (
         (f-helper (lambda (x y)
                      (if (p x y) 
                         (f-helper (g x y) y)
                         (h x y)))))
         (f-helper e y)))
    

    or this Haskellish code

    f_fun y = h x_final y
       where x_initial = e
             x_final   = loop x_initial
             loop x = if p x y then loop (g x y) else x
    

    As to why functional programmers like to do this (which you did not ask), the more pieces of your program are stateless, the more ways there are to put pieces together without having anything break. The power of the stateless paradigm lies not in statelessness (or purity) per se, but the ability it gives you to write powerful, reusable functions and combine them.

    You can find a good tutorial with lots of examples in John Hughes's paper Why Functional Programming Matters.

提交回复
热议问题