Last active
May 1, 2019 05:28
-
-
Save lagenorhynque/e3b9cd3ed214dc0f547f97cfe0d14502 to your computer and use it in GitHub Desktop.
Protocols in Elixir & Clojure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (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)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cf. Protocols - Elixir