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

Well, the second version here is better for the following reasons:

- 9 less lines of code.

- Easier to see that it's correct. Partly because it's less lines, but partly because those lines are more meaningful and less bland. It would be hard to see a typo in the repetitive inner loop of the first version.

- Two obvious independent pieces of code instead of one big piece of code. That means if you're reading it, you know how to go about understanding it; understand each piece in turn. Somewhat trivial when there are 25 lines, but serious if there are 200 lines.

- Easier to test and debug. At a REPL, it's trivial to see what the stack is going to look like five hops into the functional version; you just apply the processing function five times. To do the same to the imperative version, you need to either write some debug logic into the middle of the function or set a breakpoint and hit 'continue' in your debugger while you count on your fingers.

Those reasons are typical consequences of writing your code as a collection of data and pure functions.

Also, the semantics are not completely inherently serial for most possible stacks. The sequence of operations forms a tree of computation, and the branches of the tree could be computed in parallel. If you actually wanted to do that (say, if the operations took a long time individually) then the way you would go about it is to construct the tree explicitly up front, take this functional version, replace fold with a version of fold that knows how to fold over trees in parallel, and fold it over the tree. Ta-da -- it would just work.



Another reason the second may be better:

- Wrap the stack program in a transaction and simply discard the results to roll back the transaction. In an imperative program it is error prone to roll back a complicated operation—the most innocent looking function might mutate external state.


Well technically F# has no purity handling, so it's just as possible for the most innocent-looking F# function to have side-effects as well.


Thanks for the warning. That sucks.




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

Search: