-
-
Notifications
You must be signed in to change notification settings - Fork 4
pure
Pure functions are side effects free and do not use external information.
The opposite of pure functions are input output io and random functions.
Operators are usually pure meaning that they are side effects free and do not use global information.
Purity can be declared or inferred
square x = x*x
square.pure? true
purely square x = x*x # ok declared purity confirmed inferred purity by compiler
square.pure? true
time := now!
time.input? true # reads time from system
time.random? true # time changes and is somewhat random
time.output? false
purely calculate fibonacci number n := fib_cache[n]=fib(n) # error: function declared as pure uses externals
purely calculate fibonacci number n := return fib_cache[n] # error: function declared as pure has side effects
purely calculate fibonacci number n := fibonacci(n-1) + fibonacci(n-2) # ok, declared purity confirmed by compiler
Pure functions have the benefit that they can be inlined implicitly or explicitly on demand. Pure functions allow for a better code analysis, optimization and correctness proving. Pure functions simplify or enable type inference. Pure functions are generally a sign of good coding style.