Skip to content

Instantly share code, notes, and snippets.

@ferd
Created August 20, 2012 18:58
Show Gist options
  • Select an option

  • Save ferd/3406727 to your computer and use it in GitHub Desktop.

Select an option

Save ferd/3406727 to your computer and use it in GitHub Desktop.
%%% Macro definitions for lazy (or rather delayed) evaluation.
%% Force and delay are used in combination to delay evaluation to only
%% when strictly needed:
%% Promise = ?delay(expensive_computation(A,B,C)),
%% Value = ?force(Promise).
%%
%% These macros should be used with extreme precaution when sending a
%% function to another process as it relies on closures and the sharing of
%% information is lost when copying. So is memoization. Therefore, lazy
%% evaluation of that kind should be kept for a single process.
-define(delay(E), fun() -> E end).
-define(force(F), lazy_memoize(F)).
%% memoization uses a process dictionary. While hackish and not portable
%% through processes, a PD of this kind has the advantage of being
%% garbage collected and being returned in a stack trace. There is also no
%% copying (see: comments over the macros) or locking needed.
-define(memoize(E), lazy_memoize(fun()-> E end)).
lazy_memoize(F) when is_function(F) ->
case erlang:get(F) of
undefined ->
erlang:put(F,F()),
erlang:get(F);
X -> X
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment