Skip to content

Instantly share code, notes, and snippets.

Last active September 27, 2020 10:05
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save sheharyarn/9628dadbbf424d1f91e5734130b5a588 to your computer and use it in GitHub Desktop.
Simple Memoization in Elixir (using FastGlobal)
defmodule Memoize do
@moduledoc """
Simple memoization helper built on top of FastGlobal.
Remember to add `{:fastglobal, "~> 1.0"}` to your
dependencies first.
## Usage
def my_method do :my_method, fn ->
# return something
## Other
Author: Sheharyar Naseer
License: MIT
Find updates to this module at
# Public API
# ----------
@doc """
If previously saved value exists, return that else
perform memoization for given key and function.
def run(key, fun) when is_atom(key) do
case get!(key) do
nil ->
value = fun.()
put!(key, value)
result ->
@doc "Force get value"
defdelegate get!(key), to: FastGlobal, as: :get
@doc "Force put value"
defdelegate put!(key, value), to: FastGlobal, as: :put
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment