What If We Could Mark Pure Methods?
Craig Buchek
@CraigBuchek
github.com/booch
No side-effects
Does not mutate state
Idempotent - can run multiple times, always getting same result
def method1
1 + 1
end
def add1 ( x )
x + 1
end
def not_pure1
Random . rand
end
def not_pure2 ( x )
self . x = x
end
def not_pure3
puts "Hello!"
end
Could automatically memoize pure methods
Could be run in parallel, theoretically
Functional Programming
def method1 ( options )
# ...
end
pure :method1
# Ruby 2.1+
pure def method2 ( options )
# ...
end
@pure
def method2 (self , options ):
# ...
C++ allows marking pure methods
C++ has const
everywhere
We'd be encouraged to default to pure methods
Could we infer purity via static analysis?
We'd really have to do it in the interpreter
Fairly dramatic change to the language semantics
Considering trying to add it to Rubinius or Crystal
Marking classes as mutable/immutable
Marking instances as mutable/immutable:
x = User . new ( 'Craig' ) # immutable
y = User . new! ( 'Craig' ) # mutable