4 ms·
That may be less useful than you think, since the FP versions of many OO design patterns are just functions. The FP design patterns can end up being quite diffe
by sli 9y ago
That may be less useful than you think, since the FP versions of many OO design patterns are just functions. The FP design patterns can end up being quite different than the similar OO versions, if you can even call them design patterns.
So, all of this below is written in terms of FP beginners, so if I make a claim, it's in those terms, not general functional programming terms. I know that some of the information below is not entirely correct, just bear with me.
Some argue that FP doesn't really have design patterns, which isn't true, but can be a useful mental model to keep you from getting hung up on them while you're learning. Consider than many of OO's design patterns are built to structure mutations on data. FP, by contrast, doesn't (typically) mutate data. That's where things diverge, and that's fairly early in the learning process.
All that said, there are slews of things that can be "close enough" one-to-one mapped to an OO version, it's just that most of those things are fairly trivial. Map/filter/reduce vs. for-loops, for example.
Perhaps you could start there. Rewrite some for-loops with map/filter/reduce. Learn the rules they follow, learn what a monoid is and what laws it follows and why they're useful, go from there. Something that helped me early on was implementing each of those in terms of the others. For example, implementing filter with reduce.
Experimenting with good "playground" languages can help a lot. Hy[1] is an example of that, it's Lisp-flavored Python. You'll have a Lisp with a standard library that's very widely known, and you only need to install a Python module to use it (rather than, say, the entire Clojure stack).
The biggest takeaway is that FP is geared very heavily towards writing programs and data pipelines that are built with small, composable pieces that are ideally also associative. You can of course do this with OO, but then your code ends up looking like this:
someFunc(anotherFunc(thirdFunc(data)))
Or:
var someVal = thirdFunc(data)
var anotherVal = anotherFunc(someVal)
var finalVal = someFunc(anotherVal)
Or:
// Mutate
data = thirdFunc(data)
data = anotherFunc(data)
data = someFunc(data)
Compare to Clojure's version:
((comp third-func another-func some-func) data)
And Haskell's (might be wrong, I'm not a Haskell programmer):
(thirdFunc . anotherFunc . someFunc) data
[1]: http://docs.hylang.org/en/stable/ http://docs.hylang.org/en/stable/
- jayachdee 9y agoThe usual Haskelly way is thirdFunc . anotherFunc . someFunc $ data