Created
April 30, 2019 18:01
-
-
Save lagenorhynque/b53b8c0d5f27c9e356aced470fb83d40 to your computer and use it in GitHub Desktop.
Typespecs in Elixir & clojure.spec in 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 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!"]) |
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
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 |
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 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))) |
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cf. Typespecs and behaviours (Types and specs) - Elixir