Being relatively new to functional programming, I expend lots of energy wondering “is this the functional way to do things?” Obviously recursion vs. iteration is pretty straightforward and it’s obvious that recursion is the functional way of doing things. But take closures for instance. I’ve learned about closures using Lisp and I understand that closures are a combination of a function and an environment (sounds a lot like state and behavior). For instance:
(let ((x 1))
(defun doubleX()
(setf x (* x 2))))
Here we have a function doubleX that has been defined within the environment of the x variable. We could pass this function around to other functions and then invoke it and it will still be able to reference the x variable. The function can continue to refer to that variable, even if it is invoked outside of the environment where the variable has been defined. Many of the examples I’ve seen of closures look like this. Where setf is used to change the value of the lexical variable. This confuses me because:
1.) I thought setf was evil. Mostly because it causes side-effects and apparently they are also evil.
2.) Is this really “functional”? Seems like just a way of keeping global state and I thought functional languages were stateless.
Maybe I just don’t understand closures. Can someone help me out?