📎 Webclip
Understanding Protocols
The thread asks why a reduce function that works inside a VM module stops behaving as expected after being moved into a protocol. The example shows nested Num, Add, and Mul structs, and the failure appears when reduce is called from inside defimpl code without qualifying the protocol.
Peter Hamilton suggests calling Reduce.reduce(...) explicitly inside each implementation. José Valim explains that import is purely lexical in Elixir, so it only makes the function name available in the current file. It does not change how a module resolves calls, and Elixir normally invokes other modules directly instead of coupling behavior to data as in Ruby.
Reading notes#
- The discussion starts from a
KeyErrorraised while reducing nested arithmetic structs in Elixir. - The user expected
import ReduceinsideVMor inside the protocol implementations to make allreduceversions visible. - Peter’s fix is to qualify recursive calls with
Reduce.reduce(...). - José says
importonly affects name lookup in the current lexical scope. - He contrasts Ruby’s coupling of data and behavior with Elixir’s separation of the two.
- In Elixir, calling another module explicitly is the normal pattern, and
importis only a shortcut for omitting the module name.
