by nightcracker · 5y ago · 0 comments
There are exceptions of course, but I personally feel that there's three main 'kinds' of code:
1. functions that define some input/output relation
2. query methods on data structures
3. modification methods on data structures
4. the bodies of the above functions
In a purely functional language all four are purely functional, but this is (IMO) needlessly restrictive. It leads to recursion where iteration is more natural, awkward choices of data structures or even plain impossibility of certain algorithms/data structures (ask a functional programming zealot to implement an O(1) hash map in a pure way—they will usually stammer, try to move goal posts, before finally admitting it's not possible).Personally I feel that 1 & 2 should be 'pure' and not modify (observable) data and have the same results, but 3 & 4 are perfectly fine if not natural to be imperative and have mutable state.
Viewing iteration as more 'natural' than a fold seems down to mostly taste. And hell, if you really want iteration, you can easily get that in both effectful and non-effectul variants through monads.
>ask a functional programming zealot to implement an O(1) hash map in a pure way—they will usually stammer, try to move goal posts, before finally admitting it's not possible
Except that no one - not even Haskell zealots - will argue that you never need effects, but simply that effects should be encapsulated. In Haskell, nothing prevents you from using mutable state if you really need it and mutable hash tables can be easily implemented using something called functional state threads [1][2].
[1] https://www.microsoft.com/en-us/research/wp-content/uploads/...
I concur. My two favorite languages nowadays (Elixir and Clojure) are far from being purely functional. They are functional enough that mutating state is awkward, but if you do need it it is there.
I also think having immutable data structures by default is a saner choice IMO.
> It leads to recursion where iteration is more natural, awkward choices of data structures or even plain impossibility of certain algorithms/data structures
Anecdotal, but I rarely use recursion/for loops, opting for defining auxiliary functions that works in one element and using map/reduce instead. Really, I don't remember the last time I needed recursion to solve a problem (for example, I know recur exists in Clojure, but I never saw it in the code that I work everyday).
Same here. I use c# and Typescript mostly. In c# you can use Select for map, Aggregate for reduce and there's a huge selection of other list processing operations that make use of lambda expressions. In typescript/javascript there map, reduce, etc