Jeanine Adkisson - Variants are Not Unions
Why Stack Overflow recommends it
Stack Overflow users link it when answering how to represent sum types or tagged variants in Clojure, especially with core.match and vectors.
Recommended by 1 people across 1 different months, 2015 to 2016.
What it is
A Clojure/West-style conference talk by Jeanine Adkisson on tagged unions (variants) in Clojure. She shows how to build and destructure variants with core.match, type them with core.typed, and store them in Datomic.
What people said
Recommends optevo · 2016-11 · Stack Overflow · on “Idiomatic way to represent sum type (Either a b) in Clojure”
Use a vector with the tag as the first element in a vector and the use core.match to destructure the tagged data. Hence for the example above, the "either" data would be encoded as: [:left 123] [:right "hello"] To then destructure you would need to refer to core.match [LINK] and use: (match either [:left num-val] (do-something-to-num num-val) [:right str-val] (do-something-to-str str-val)) This is more concise than the other answers. This youtube talk [this video] gives a more detailed explanation of why vectors are desirable for encoding variants over maps. My summary is that using maps to encode variants is problematic because you have to remember the map is a "tagged map" not a regular map. To
Cites miguel · 2015-07 · Stack Overflow · on “Clojure core match error with variant”
I'm trying to solve this [LINK] SICP exercise using clojure with core/match and core/typed. I'm kind of following Jeanine Adkisson's "Variants are Not Unions" [this video] talk. This is what I got so far: (ns sicp.chapter2_ex29 (:require [clojure.core.typed :as t] [clojure.core.match :refer [match]])) ; Type definitions (t/defalias Mobile '{:left Branch, :right Branch}) (t/defalias Weight Number) (t/defalias Structure (t/U '[(t/Value :weight) Weight] '[(t/Value :mobile) Mobile])) (t/defalias Branch '{:length Number, :structure Structure}) ; Constructors (t/ann make-mobile [Branch Branch -> Mobile]) (defn make-mobile [left right] {:left left :right right}) (t/ann make-branch [Number Structure -> B
Cites Magos · 2015-08 · Stack Overflow · on “Idiomatic expression simplification in Clojure”
Not sure about being the idiomatic implementation, but I think as Guillermo Winkler mentioned core.match is a pretty natural alternative approach, especially with variants [this video] . As your linked article says, sum types are pretty neat. (ns simplify (:require [clojure.core.match :refer [match]])) (defn- simplify-1 [expr] (match expr [::add [::const 0] a] a [::add a [::const 0]] a [::add [::const a] [::const b]] [::const (+ a b)] [::mult [::const 0] _] [::const 0] [::mult _ [::const 0]] [::const 0] [::mult a [::const 1]] a [::mult [::const 1] a] a [::mult [::const a] [::const b]] [::const (* a b)] _ expr)) (defn simplify [expr] (match expr [::add a b ] (simplify-1 [::add (simplify a) (simpli