Skip to content

Instantly share code, notes, and snippets.

@straight-shoota
Created June 7, 2017 21:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save straight-shoota/3ef2fe2f597a4306ef9b84d195f81bf3 to your computer and use it in GitHub Desktop.
Save straight-shoota/3ef2fe2f597a4306ef9b84d195f81bf3 to your computer and use it in GitHub Desktop.
Memoize in Crystal
macro memoize(type_decl, &block)
@{{type_decl.var}} : {{ type_decl.type }} | UninitializedMemo = UninitializedMemo::INSTANCE
def {{type_decl.var}}
if (value = @{{type_decl.var}}).is_a?(UninitializedMemo)
@{{type_decl.var}} = begin
{{block.body}}
end
else
value
end
end
end
class UninitializedMemo
INSTANCE = new
end
class ClassName
memoize expensive_query : Int32 do
puts "hello"
"hello".size
end
end
puts ClassName.new.expensive_query
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment