Nate's first type programming

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
42
43
44
45
46
47
48
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module TypeLevel.DatePart where
import Prelude hiding (break)

data a :/: b = a :/: b deriving (Eq, Ord)
infixr :/:

class Seq a x y where
    break :: x -> (a, y)
    build :: a -> y -> x

instance (Seq a x y, Seq b y z) => Seq (a :/: b) x z where
    break x = let
        (a, y) = break x :: (a, y)
        (b, z) = break y :: (b, z)
        in (a :/: b, z)

    build (a :/: b) z = let
        y = build b z :: y
        x = build a y :: x
        in x

data Foo = Foo Integer
instance Seq Foo Integer Bool where
    break i | i >= 0 = (Foo $ abs i, True)
            | otherwise = (Foo i, False)
    build (Foo i) True = i
    build (Foo i) False = negate i

data Bar = First | Second
instance Seq Bar Bool Bar where
    break True = (First, First)
    break False = (Second, Second)
    build First _ = True
    build Second _ = True

data Baz = Baz Bar
instance Seq Baz Bar () where
    break b = (Baz b, ())
    build (Baz b) _ = b

myBreak :: Integer -> (Foo :/: Bar :/: Baz)
myBreak = fst . break' where
    break' = break :: Integer -> (Foo :/: Bar :/: Baz, ())