aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/data/sum.lux
blob: 716b3908afc8bdd583dc912bf4651e89f5b1e42c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
(;module: {#;doc "Functionality for working with variants (particularly 2-variants)."}
  lux)

## [Values]
(do-template [<name> <type> <index>]
  [(def: #export (<name> value)
     (All [a b] (-> <type> (| a b)))
     (<index> value))]

  [left  a +0]
  [right b +1])

(def: #export (either f g s)
  (All [a b c] (-> (-> a c) (-> b c) (| a b) c))
  (case s
    (+0 x)  (f x)
    (+1 x) (g x)))

(do-template [<name> <side> <tag>]
  [(def: #export (<name> es)
     (All [a b] (-> (List (| a b)) (List <side>)))
     (case es
       #;Nil                  #;Nil
       (#;Cons (<tag> 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 x')  [(#;Cons x' lefts) rights]
        (+1 x') [lefts (#;Cons x' rights)]))))