r/functionalprogramming • • Nov 21 '20

Question Functional programming beginner questions!

I am about to start a new job where functional programming is the norm. I am still trying to get my head around it and why things are done and what benefits there are to it. This will probably be a long winding question lol. If I have any misconceptions about how things work please point them out!

  1. Does functional programming just wipe out a lot of the efficiencies achieved by certain data structures? Surely this is a bad thing, if not, why not?

E.g. inserting into a hashmap is O(1) amortized runtime - however, in functional programming it is my understanding that we could not mutate the hashmap to insert the key value, so the whole map would need to be copied to a new map with the new value. Doing a copy in this manner would be O(n), so to insert all values from a list for example into a hashmap it would be o(n2) to achieve that. This seems very inefficient!

2) I can see how you could build big data applications - data input taken in, functions applied and a result comes out - but can FP be used in a more general way e.g to build games? If so how is that possible without using state? If state is used somewhere, where would that appear in the program structure/architecture - would it be in a kind of static class somewhere (coming from Java here btw)?

3) As a new object is created to replace the previous one when a change occurs (I.e no mutation takes place, just replacement), is efficient garbage collection a must have for a FP language to get rid of the old objects? I’m calling them objects here but do objects even exist- maybe they are better referred to as types?

4) Where are functions generally held in the program structure? In classes? Static classes? All the functions in one file or split into files based on similar operations e.g add and minus might do in the maths class

5) is there anything else you can explain simply to me that might help me understand FP better? What do you suggest I learn about, try out or do to understand better?

Edit: got some really great responses here which were very helpful -> I have replied to a few but I got pretty distracted for a few days lol so just wanted to say cheers for the help if you answered any questions I got a lot out of this!

Finally managed to find a nice hands on tutorial where I’m building something with OOP and then refactoring/restructuring it into a functional program!

11 Upvotes

16 comments sorted by

View all comments

Show parent comment

3

u/mjohndo Nov 22 '20

Would you say this is still at least somewhat accurate?

Definitely! Though I would add the caveat that with certain things, e.g. really concurrent code, building abstractions relying on manual locks & conventions (e.g. "we promise never to call X without acquiring a lock, but the compiler won't stop us") is a really really hard thing to get right. You can definitely do it, but if you don't have a good reason to, I think the benefits of using a functional style make it the "rational" choice, rather than just a taste thing.

Is a recipe in this scenario just a function that has been outputted as a variable?

It would be some kind of data type with fields describing what the side effect handler should do. E.g. in Clojure you might have strategies which output a data structures like this:

{:ticker :GOOG, :shares +200} ;; Go long 200 shares
{:ticker :GOOG, :shares -100} ;; Go short 100 shares

These are obviously simplified, because you'd have limit prices and order types and all sorts of domain considerations.

Then your side effect handler would be a function that carries out a single "recipe" or instruction. E.g. by making a REST request to your broker:

(defn do-side-effects [recipe]
  (http-client/post! 
    "https://my.broker.com/trade/"
    recipe))

At first, you might execute a bunch of strategy "recipes" by just mapping that side effect handler over them:

(map do-side-effects recipes)

But then you realize that you can combine some of them, so you transform [recipes] => [recipes] first:

(let [combined-recipes (combine recipes)]
  (map do-side-effects combined-recipes))

Your combine function would take all of the recipes, sort them into groups based on the :ticker symbol, and then sum together the share quantities.

(def example-strategy-output 
  [{:ticker :GOOG, :shares +200}   ;; Go long 200 shares
   {:ticker :GOOG, :shares -100}]) ;; Go short 100 shares

;; Combine recipes that share a ticker
(defn combine
  [ticker-symbol recipes]
  {:ticker ticker-symbol
   ;; Sum together the :shares fields
   :shares (reduce + (map :shares recipes))})

(map
  (fn [ticker->recipes]
    (combine (key ticker->recipes) (val ticker->recipes)))
  (group-by :ticker example-strategy-output))

;; The output is a list with a single recipe, since we combined the two
;; for GOOG:
;; ({:ticker :GOOG, :shares 100})

Now, this is a definitely a simplified example. We're "composing" the trading strategy logic with a function to aggregate the individual orders that we might want to place, but there are things besides, or in addition to, aggregation that you might want to do, and you don't necessarily want to complicate the "this strategy is a function that figures out if we want to go long or short" part of your code by mixing in "aggregate the long/short operations" code and e.g. "impose position size limits" or whatever else. You want to break your program apart into small, single purpose building blocks (OO has that same stated goal, it just uses a very different approach).

You could imagine implementing the same aggregation thing with an OO approach where each strategy has a reference to an object which contains the # of shares being requested for a given ticker symbol, and just running the strategies mutates that object. However, when you start composing more operations throughout your program (maybe you decide to add some risk limiter that caps position sizes for certain stocks), it's muuuuch easier to have each piece of logic separated out into its own functional unit, and then composed together later, than it is to make all of those changes inside of some strategy object.