DEV Community

Discussion on: Mere Functional Programming in F#

Collapse
 
rhymes profile image
rhymes

Thanks Kasey, it was a great read!

I've noticed how I adopt a vaguely similar style with Python: composable testable pure functions as much as possible, isolated functions with side effects, the module as a unit of separation and encapsulation, no private (which doesn't really exist in the first place).

The big thing missing from my "functional style" in Python is recursion since it doesn't do tail call optimizations.

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

That's great to hear! I figured I couldn't be the only one who arrived at this style, regardless of language.

That actually brings up a good point that I forgot to mention -- why FP uses recursion for looping. It is because recursion allows you to loop without using mutations. Whereas for and while loops use mutable variables to control looping.

However, think about this: TCO turns the "pure" recursive loop into a functionally-equivalent imperative while loop. So it must be that mutation isn't so bad. And in fact, a function can use mutation and still be deterministic as long as the mutations are local. Meaning only values declared inside the function are mutated -- nothing from outside.

So anyway, recursion does help looping to be more declarative, but it isn't strictly necessary with a little discipline instead. :)

Collapse
 
rhymes profile image
rhymes • Edited

And in fact, a function can use mutation and still be deterministic as long as the mutations are local.

Yes, though it's not always the case in reality, many for loops have side effect in imperative programs :D

An interesting example of an improvement: Go loop variables are scoped within the loop, you can't access them from outside the loop.

Thread Thread
 
kspeakman profile image
Kasey Speakman • Edited

For sure, it is otherwise normal to perform external side effects in for loops. Just to say that with some discipline it can be avoided. Though I think that way of doing things is pretty foreign to most of us.

Collapse
 
pim profile image
Pim

This sounds very cool! Got any examples of this?