↓ Ir para o conteúdo principal

← todas as notas

📎 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 KeyError raised while reducing nested arithmetic structs in Elixir.
  • The user expected import Reduce inside VM or inside the protocol implementations to make all reduce versions visible.
  • Peter’s fix is to qualify recursive calls with Reduce.reduce(...).
  • José says import only 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 import is only a shortcut for omitting the module name.