Skip to content

Instantly share code, notes, and snippets.

@booch
Last active January 3, 2016 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save booch/8411351 to your computer and use it in GitHub Desktop.
Save booch/8411351 to your computer and use it in GitHub Desktop.
What If We Could Mark Methods As Pure?

What If We Could Mark Pure Methods?

Me

  • Craig Buchek
  • @CraigBuchek
  • github.com/booch

What is a pure method?

  • 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

Why?

  • Could automatically memoize pure methods
  • Could be run in parallel, theoretically
  • Functional Programming

Marking pure methods

def method1(options)
  # ...
end
pure :method1
# Ruby 2.1+
pure def method2(options)
  # ...
end
@pure
def method2(self, options):
  # ...

But

  • C++ allows marking pure methods
  • C++ has const everywhere

Marking impure methods

  • We'd be encouraged to default to pure methods

Inference

  • Could we infer purity via static analysis?

But

  • 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

Going even further

  • Marking classes as mutable/immutable
    • More value objects!
  • Marking instances as mutable/immutable:
x = User.new('Craig')   # immutable
y = User.new!('Craig')  # mutable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment