I touched on the topic of mem­o­iza­tion in the past in rela­tion to doing aspect-oriented pro­gram­ming with Post­Sharp, how­ever, with func­tional 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­tional lan­guage though, in fact, here’s a sim­ple imple­men­ta­tion of the afore­men­tioned mem­o­izer in F# as a higher-order function:

image

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

image

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 anytime.

Part­ing 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­ested 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-memoized ver­sion of the func­tion, it’ll require some spe­cial han­dling to make a recur­sive func­tion ‘memoizable’.

In gen­eral, I don’t feel AOP is as well suited to func­tional pro­gram­ming as it is to object ori­ented pro­gram­ming, but there’s still a pocket of use cases 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 higher-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 higher-order func­tions is not going to be as unob­tru­sive as you’re used to.

Share

Leave a Reply