by rightbyte · 3y ago · 0 comments
My main beef with functional programming is that you essentially put the state in the "instruction pointer" and its history of walking the call stack instead of bound to symbols. It does not fit my way of thought. I personally prefer more or less statemachines.
Basically how FP sells:
def a
1
end
def b
2
end
def c
a + b
end
You see? c = 3! Now try to apply this logic to (real world with effects): def a
(conn: DBConn) => { .... some complex code ... }
end
def b
(conn: DBConn) => { .. another complex code ... }
end
def c
(conn: DBConn) => a(conn) + b(conn)
end
So c = ? Still transparent?No, it's not. and a and b are neither in your second example, otherwise they could not produce any result that could be combined with +. Unless `{ .... some complex code ... }` is just `return 42`.
Referential transparency means that we can evaluate the same thing over and over again and getting exactly the same value back. Obviously that does not work with what you have constructed.
It helps when you annotate your examples with return types. That will make things clear very quickly.
We’re talking about something that starts with things like reduce vs. a for loop with mutable variables to accumulate values. Once the language forces you to think in terms of stateful operations to perform even basic tasks, the reflexive tendency is to use mutable state to perform any task. At that point, nobody really knows what a functional does because you have to understand the entire system to know what the output of a function will be.
Besides, it's good practice to limit how widespread side effects are in any program, anyway.
Monads is a nice way to hide state I have to admit, but not because of referential transparency and "reasoning".
In functional programming, we think of computation as reducing an expression; a computation is complete when it can't be reduced anymore. In imperative programming, we think of computation as updating a store of data; a computation is complete when we run out of steps to perform.
When you're partway through execution, the "rest of the program" in an imperative system is captured by the current state of the store (including the stack). In a functional program, the "rest of the program" is just the program expression itself, reduced as it has been up to this point.
I tend to like the functional model, myself, but I can see the mental appeal of keeping the program text fixed, and isolating all changes to a separate store of data.