Created
June 7, 2017 21:30
-
-
Save straight-shoota/3ef2fe2f597a4306ef9b84d195f81bf3 to your computer and use it in GitHub Desktop.
Memoize in Crystal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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