Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I think saying that FP is bad for "manipulating state" is misleading.

FP is great at manipulating state. A pure Haskell function (State -> State) manipulates state.

What's being discussed is whether or not the state is manipulated destructively. And personally I don't see any real benefits to the destructive method, except performance issues in some cases, and arguably stylistic ones.

Returning new values instead of in-place updates may seem cumbersome before you get to know the abstractions that make it easy to use.

As an example, in Haskell, if you want to update a value deep inside multiple nested records, you do something like:

    movePlayer :: (Pos -> Pos) -> GameState -> GameState
    movePlayer f gs = gs { player = oldPlayer { position = f oldPos } }
      where
        oldPlayer = player gs
        oldPos = position oldPlayer
That looks horrible, compared to something like:

    gs.player.position = f(gs.player.position);
But then, if you discover the Semantic Editor Combinators abstraction (http://conal.net/blog/posts/semantic-editor-combinators/), then you can write that as:

    movePlayer :: (Pos -> Pos) -> GameState -> GameState
    movePlayer f = (atPlayer . atPosition) f
or just:

    movePlayer = atPlayer . atPosition
Then you can use:

    movePlayer (+delta)

to add delta to the position.

Now one nice thing about the return-new-value approach is that it is more composable than the destructive update approach. When you compose state manipulation functions, you get transactional state changes.

So paradoxically, I believe functional languages to be better at manipulating state!



Consider applying for YC's Winter 2027 batch! Applications are open till November 2.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: