Skip to content

Instantly share code, notes, and snippets.

@lagenorhynque
Last active May 1, 2019 05:28
Show Gist options
  • Select an option

  • Save lagenorhynque/e3b9cd3ed214dc0f547f97cfe0d14502 to your computer and use it in GitHub Desktop.

Select an option

Save lagenorhynque/e3b9cd3ed214dc0f547f97cfe0d14502 to your computer and use it in GitHub Desktop.
Protocols in Elixir & Clojure
(ns generic-size)
(defprotocol Size
(size' [data] "Calculates the size (and not the length!) of a data structure"))
(extend-protocol Size
String
(size' [s] (count s))
clojure.lang.IPersistentMap
(size' [m] (count m))
clojure.lang.IPersistentVector
(size' [v] (count v))
clojure.lang.IPersistentSet
(size' [v] (count v))
;; fallback implementation
Object
(size' [_] 0)
nil
(size' [_] 0))
(defrecord User [name age]
Size
(size' [_] 2))
defprotocol Size do
@fallback_to_any true
@doc "Calculates the size (and not the length!) of a data structure"
def size(data)
end
defimpl Size, for: BitString do
def size(string), do: byte_size(string)
end
defimpl Size, for: Map do
def size(map), do: map_size(map)
end
defimpl Size, for: Tuple do
def size(tuple), do: tuple_size(tuple)
end
defimpl Size, for: MapSet do
def size(set), do: MapSet.size(set)
end
defmodule User do
defstruct [:name, :age]
end
defimpl Size, for: User do
def size(_), do: 2
end
defimpl Size, for: Any do
def size(_), do: 0
end
@lagenorhynque
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment