4 ms·
It depends how deep you want to go. I would say that 'functional' can mean different thing to different people, but usually I see it as methodical use of certai
by a-saleh 9y ago
It depends how deep you want to go. I would say that 'functional' can mean different thing to different people, but usually I see it as methodical use of certain programming features over others.
1. Language supports functions as values, anonymous functions, has higher order functions, and ability for functions to access scope in closure. At this base level there are no disadvantages to prefer using these, because they allow some nice abstractions (as evidenced by many functional libs in js.)
2. using recursion over loops, can be a good fit for expressing some algorithms. Often requires some support for optimisation in language (i.e. tco, so that your stack doesn't explode. In my experience you'd use higher order functions like map, fold/reduce most of the time anyway, instead of dealing with loops/recursion directly.
3. pure functions. This is the first interesting trade-of in functional programming, how much should you use functions that only depend on its inputs to provide its output (and for the same input output would stay the same). There are clear advantages, you can test these well, understand them in isolation, refactor them easier, memoization is almost for free.
On the other hand, only using pure functions would limit the usefulness of the language (it is said that first version of haskell was only able to do a transformation from stdin to stdout, because they had just pure functions) Languages that are big on being 'pure' usually allow you to make impure functions, but then track their usage in the type-system. This was one of those things, that I often think is more trouble than is worth.
4. immutable data-structures, which come in handy when you want to create pure functions that would rather return a copy with modifications, than modify in-place (because that might have unintended consequences elsewhere) It takes some time to get used to these, but their performance is on par with regular datastructures nowdays.
5. lazyness, where you compute only when necessary. Can make certain programs more efficient and easier to comprehend, others harder, i.m.o
6. no global state.
7. comprehensive type system is sometimes viewed as necessary for real functional language (how else would you check you don't do side-effects in wrong places)
For me, 1., 3., 4. and 6. are those I consider important and with little drawbacks to try to use them 80-90% of time.