Skip to content

Instantly share code, notes, and snippets.

@killme2008
Created October 23, 2015 04:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killme2008/f192804eee700511642c to your computer and use it in GitHub Desktop.
Save killme2008/f192804eee700511642c to your computer and use it in GitHub Desktop.
Elixir protocols example
defprotocol Blank do
@doc "Returns true if data is considered blank/empty"
@fallback_to_any true
def blank?(data)
end
defimpl Blank, for: Any do
def blank?(_), do: false
end
# Just empty list is blank
defimpl Blank, for: List do
def blank?([]), do: true
def blank?(_), do: false
end
# Just empty map is blank
defimpl Blank, for: Map do
# Keep in mind we could not pattern match on %{} because
# it matches on all maps. We can however check if the size
# is zero (and size is a fast operation).
def blank?(map), do: map_size(map) == 0
end
# Just the atoms false and nil are blank
defimpl Blank, for: Atom do
def blank?(false), do: true
def blank?(nil), do: true
def blank?(_), do: false
end
@killme2008
Copy link
Author

(defprotocol Blank
  (blank? [this] "Returns true if data is considered blank/empty"))

(extend-protocol Blank
  clojure.lang.IPersistentMap
  (blank? [this]
    (= {} this))
  clojure.lang.IPersistentVector
  (blank? [this]
    (= [] this))
  String
  (blank? [this]
    (.isEmpty this))
  nil
  (blank? [this]
    true)
  false
  (blank? [this]
    true)
  Object
  (blank? [this]
    false))

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