aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/data/sum.lux
diff options
context:
space:
mode:
authorEduardo Julian2021-07-14 13:59:02 -0400
committerEduardo Julian2021-07-14 13:59:02 -0400
commitd6c48ae6a8b58f5974133170863a31c70f0123d1 (patch)
tree008eb88328009e2f3f07002f35c0378a8a137ed0 /stdlib/source/library/lux/data/sum.lux
parent2431e767a09894c2f685911ba7f1ba0b7de2a165 (diff)
Normalized the hierarchy of the standard library modules.
Diffstat (limited to 'stdlib/source/library/lux/data/sum.lux')
-rw-r--r--stdlib/source/library/lux/data/sum.lux90
1 files changed, 90 insertions, 0 deletions
diff --git a/stdlib/source/library/lux/data/sum.lux b/stdlib/source/library/lux/data/sum.lux
new file mode 100644
index 000000000..7a439fc54
--- /dev/null
+++ b/stdlib/source/library/lux/data/sum.lux
@@ -0,0 +1,90 @@
+(.module:
+ {#.doc "Functionality for working with variants (particularly 2-variants)."}
+ [library
+ [lux #*
+ [abstract
+ [equivalence (#+ Equivalence)]
+ [hash (#+ Hash)]]]])
+
+(template [<name> <type> <right?>]
+ [(def: #export (<name> value)
+ (All [a b] (-> <type> (| a b)))
+ (0 <right?> value))]
+
+ [left a #0]
+ [right b #1])
+
+(def: #export (either fl fr)
+ (All [a b c]
+ (-> (-> a c) (-> b c)
+ (-> (| a b) c)))
+ (function (_ input)
+ (case input
+ (0 #0 l) (fl l)
+ (0 #1 r) (fr r))))
+
+(def: #export (apply fl fr)
+ (All [l l' r r']
+ (-> (-> l l') (-> r r')
+ (-> (| l r) (| l' r'))))
+ (function (_ input)
+ (case input
+ (0 #0 l) (0 #0 (fl l))
+ (0 #1 r) (0 #1 (fr r)))))
+
+(template [<name> <side> <right?>]
+ [(def: #export (<name> es)
+ (All [a b] (-> (List (| a b)) (List <side>)))
+ (case es
+ #.Nil
+ #.Nil
+
+ (#.Cons (0 <right?> x) es')
+ (#.Cons [x (<name> es')])
+
+ (#.Cons _ es')
+ (<name> es')))]
+
+ [lefts a #0]
+ [rights b #1]
+ )
+
+(def: #export (partition xs)
+ (All [a b] (-> (List (| a b)) [(List a) (List b)]))
+ (case xs
+ #.Nil
+ [#.Nil #.Nil]
+
+ (#.Cons x xs')
+ (let [[lefts rights] (partition xs')]
+ (case x
+ (0 #0 x') [(#.Cons x' lefts) rights]
+ (0 #1 x') [lefts (#.Cons x' rights)]))))
+
+(def: #export (equivalence left right)
+ (All [l r] (-> (Equivalence l) (Equivalence r) (Equivalence (| l r))))
+ (implementation
+ (def: (= reference sample)
+ (case [reference sample]
+ [(#.Left reference) (#.Left sample)]
+ (\ left = reference sample)
+
+ [(#.Right reference) (#.Right sample)]
+ (\ right = reference sample)
+
+ _
+ false))))
+
+(def: #export (hash left right)
+ (All [l r] (-> (Hash l) (Hash r) (Hash (| l r))))
+ (implementation
+ (def: &equivalence
+ (..equivalence (\ left &equivalence)
+ (\ right &equivalence)))
+ (def: (hash value)
+ (case value
+ (#.Left value)
+ (\ left hash value)
+
+ (#.Right value)
+ (\ right hash value)))))