Skip to content

Commit f45e88f

Browse files
author
Thomas Mahler
committed
more idiomatic handling for bools
1 parent 11d9fec commit f45e88f

2 files changed

Lines changed: 30 additions & 7 deletions

File tree

src/CCC/CatExpr.hs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,29 @@ instance FixCat CatExpr where
108108
applyF :: CatExpr z (CatExpr a b) -> CatExpr z a -> CatExpr z b
109109
applyF f x = Apply . fanC f x
110110

111+
-- | Reify a Haskell Bool into a Scott-encoded selector.
112+
scottBool :: Bool -> CatExpr (a, a) a
113+
scottBool True = Snd
114+
scottBool False = Fst
115+
116+
-- | Scott-encoded NOT: swap the selector.
117+
scottNot :: CatExpr (a, a) a -> CatExpr (a, a) a
118+
scottNot Snd = Fst
119+
scottNot Fst = Snd
120+
scottNot _ = error "scottNot: expected Fst or Snd"
121+
122+
-- | Scott-encoded AND: if a then b else FALSE.
123+
scottAnd :: CatExpr (a, a) a -> CatExpr (a, a) a -> CatExpr (a, a) a
124+
scottAnd Fst _ = Fst
125+
scottAnd Snd b = b
126+
scottAnd _ _ = error "scottAnd: expected Fst or Snd"
127+
128+
-- | Scott-encoded OR: if a then TRUE else b.
129+
scottOr :: CatExpr (a, a) a -> CatExpr (a, a) a -> CatExpr (a, a) a
130+
scottOr Snd _ = Snd
131+
scottOr Fst b = b
132+
scottOr _ _ = error "scottOr: expected Fst or Snd"
133+
111134
instance Eq (CatExpr a b) where
112135
f == g = f Prelude.== g
113136

src/CCC/Interpreter.hs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ module CCC.Interpreter (interp) where
1818

1919
import CCC.Cat (Cartesian (fstC, sndC, dupC), Monoidal (parC),
2020
NumCat (addC, mulC, subC))
21-
import CCC.CatExpr (CatExpr (..))
21+
import CCC.CatExpr (CatExpr (..), scottBool)
2222
import CCC.Hask ()
2323

2424
interp :: CatExpr a b -> (a -> b)
@@ -40,12 +40,12 @@ interp Neg = negate
4040
interp Mul = mulC
4141
interp (Lift f) = f
4242
-- Comparison operators return Scott-encoded booleans:
43-
-- TRUE = Snd (selects second), FALSE = Fst (selects first)
44-
interp Eql = \(x, y) -> if x == y then Snd else Fst
45-
interp Leq = \(x, y) -> if x <= y then Snd else Fst
46-
interp Geq = \(x, y) -> if x >= y then Snd else Fst
47-
interp Les = \(x, y) -> if x < y then Snd else Fst
48-
interp Gre = \(x, y) -> if x > y then Snd else Fst
43+
-- scottBool reifies Haskell Bool into CatExpr selectors (TRUE=Snd, FALSE=Fst)
44+
interp Eql = scottBool . uncurry (==)
45+
interp Leq = scottBool . uncurry (<=)
46+
interp Geq = scottBool . uncurry (>=)
47+
interp Les = scottBool . uncurry (<)
48+
interp Gre = scottBool . uncurry (>)
4949
-- Fixpoint: step function is a CatExpr morphism, recursion stays categorical
5050
interp (Fix step) = \a ->
5151
let rec = Fix step

0 commit comments

Comments
 (0)