Skip to content

Instantly share code, notes, and snippets.

@lagenorhynque
Created April 30, 2019 18:01
Show Gist options
  • Save lagenorhynque/b53b8c0d5f27c9e356aced470fb83d40 to your computer and use it in GitHub Desktop.
Save lagenorhynque/b53b8c0d5f27c9e356aced470fb83d40 to your computer and use it in GitHub Desktop.
Typespecs in Elixir & clojure.spec in Clojure
(ns lousy-calculator
(:require [clojure.spec.alpha :as s]))
(s/def ::number-with-remark (s/tuple number? string?))
(s/fdef add
:args (s/cat :x number?
:y number?)
:ret ::number-with-remark)
(defn add [x y] [(+ x y) "You need a calculator to do that?!"])
(s/fdef multiply
:args (s/cat :x number?
:y number?)
:ret ::number-with-remark)
(defn multiply [x y] [(* x y) "Jeez, come on!"])
defmodule LousyCalculator do
@typedoc """
Just a number followed by a string.
"""
@type number_with_remark :: {number, String.t}
@spec add(number, number) :: number_with_remark
def add(x, y), do: {x + y, "You need a calculator to do that?!"}
@spec multiply(number, number) :: number_with_remark
def multiply(x, y), do: {x * y, "Jeez, come on!"}
end
(ns quiet-calculator
(:require [clojure.spec.alpha :as s]
lousy-calculator))
(s/fdef make-quiet
:args (s/cat :number-with-remark :lousy-calculator/number-with-remark)
:ret number?)
(defn- make-quiet [[num _]] num)
(s/fdef add
:args (s/cat :x number?
:y number?)
:ret number?)
(defn add [x y] (make-quiet (lousy-calculator/add x y)))
defmodule QuietCalculator do
@spec add(number, number) :: number
def add(x, y), do: make_quiet(LousyCalculator.add(x, y))
@spec make_quiet(LousyCalculator.number_with_remark) :: number
defp make_quiet({num, _remark}), do: num
end
@lagenorhynque
Copy link
Author

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