Function caching through pattern matching

72 views
Skip to first unread message

Shyam Sankaran

unread,
Sep 14, 2016, 11:15:42 PM9/14/16
to elixir-lang-core
I was reading about metaprgramming in elixir where Chris explains how easily elixir provides unicode support in a few lines of code through pattern matching. I thought it would be a cool idea to cache functions by generating code which defines the function with the previously passed parameters as input and the computed value as the body of the function. Next time, instead of evaluating the function, you just have to pattern match !!!

Lets assume a function:

def add(a,b) do: a+b

add(1,2)  -> evaluates 1+2 = 3 -> spawn a function that creates a function : def add(1,2) do: 3 
add(1,2) -> pattern matches with  add(1,2) -> returns 3

thoughts?



OvermindDL1

unread,
Sep 15, 2016, 9:55:49 AM9/15/16
to elixir-lang-core
For something as simple as addition the pattern matching would gain no speed, but in more complex things it could, however you would not know the answer ahead of time for that so usually something like ETS is used to cache like that.

Shyam Sankaran

unread,
Sep 15, 2016, 9:01:44 PM9/15/16
to elixir-lang-core
Agreed. But, there are some functions which may have complex computations but still are idempotent. Eg. Sorting, filtering . All elixir elements being immutable definitely helps.

Thinking further, for example, a function that gets something from db which does not change frequently (a user, maybe) might be a good use case. Definitely saves some good performance. However, after some time the function becomes "unreliable", because the user data is bound to change at some time, right.

So, for the above problem, what if the function was not permanent? Lets call it "Transient function". It expires after some time!! I define a function and decorate with some metadata which specifies whether its execution must be cached. If so how long?. Something like:

cache get_usr ,ttl: 10
def get_usr do: get_from_db

Don't know, if it is even possible. just some crazy thoughts :)

OvermindDL1

unread,
Sep 16, 2016, 10:24:30 AM9/16/16
to elixir-lang-core
That definitely sounds like something like the Cachex library.  :-)
Reply all
Reply to author
Forward
0 new messages