AOP with F# — Memoization using higher-order functions

I touched on the top­ic of mem­o­iza­tion in the past in rela­tion to doing aspect-ori­ent­ed pro­gram­ming with Post­Sharp, how­ev­er, with func­tion­al lan­guages like F#, Haskell or Erlang there is no such frame­works (although Post­Sharp should still work with F# to some extent) to help you.

That’s not to say that you can’t do AOP in a func­tion­al lan­guage though, in fact, here’s a sim­ple imple­men­ta­tion of the afore­men­tioned mem­o­iz­er in F# as a high­er-order func­tion:


Here’s a FSI ses­sion that shows the mem­o­ize func­tion in action:


Note that the mem­o­ized ver­sion of the orig­i­nal func­tion f took a sec­ond to exe­cute the first time around but then sub­se­quent calls didn’t take any­time.

Parting thoughts…

The imple­men­ta­tion I’ve shown here is a very basic and only works for func­tions that takes in a sin­gle para­me­ter, if you can think of an ele­gant way to make it sup­port func­tions with dif­fer­ent num­ber of inputs please feel free to con­tact me as I’m very inter­est­ed to hear about your thoughts.

Also, this imple­men­ta­tion won’t work with recur­sive func­tions because when the func­tion recurs it will be call­ing the non-mem­o­ized ver­sion of the func­tion, it’ll require some spe­cial han­dling to make a recur­sive func­tion ‘mem­o­iz­able’.

In gen­er­al, I don’t feel AOP is as well suit­ed to func­tion­al pro­gram­ming as it is to object ori­ent­ed pro­gram­ming, but there’s still a pock­et of use cas­es where AOP can be ben­e­fi­cial. Mem­o­iza­tion is one of them, so is trac­ing and input val­i­da­tion, all of which is pos­si­ble through the use of high­er-order func­tions. A word of warn­ing though, If you’re famil­iar with frame­works such as Post­Sharp, the AOP expe­ri­ence you’re going to get through high­er-order func­tions is not going to be as unob­tru­sive as you’re used to.