6 class serialize a where
7 write :: a [String] -> [String]
8 read :: [String] -> Maybe (a, [String])
11 :: EITHER a b = LEFT a | RIGHT b
12 :: PAIR a b = PAIR a b
13 :: CONS a = CONS String a
15 :: ListG a :== EITHER (CONS UNIT) (CONS (PAIR a [a]))
17 fromList :: [a] -> ListG a
18 fromList [] = LEFT (CONS "Nil" UNIT)
19 fromList [x:xs] = RIGHT (CONS "Cons" (PAIR x xs))
21 toList :: (ListG a) -> [a]
22 toList (LEFT (CONS "Nil" UNIT)) = []
23 toList (RIGHT (CONS "Cons" (PAIR x xs))) = [x:xs]
25 :: BinG a :== EITHER (CONS UNIT) (CONS (PAIR (Bin a) (PAIR a (Bin a))))
26 :: Bin a = Leaf | Bin (Bin a) a (Bin a)
28 fromBin :: (Bin a) -> BinG a
29 fromBin Leaf = LEFT (CONS "Leaf" UNIT)
30 fromBin (Bin l a b) = RIGHT (CONS "Bin" (PAIR l (PAIR a b)))
32 toBin :: (BinG a) -> Bin a
33 toBin (LEFT (CONS "Leaf" UNIT)) = Leaf
34 toBin (RIGHT (CONS "Bin" (PAIR l (PAIR a b)))) = Bin l a b
36 instance serialize Int
38 write i c = [toString i:c]
39 read [i:c] = Just (toInt i, c)
42 instance serialize [a] | serialize a
44 write a c = write (fromList a) c
45 read c = case read c of
46 Just (l, c) = Just (toList l, c)
49 instance serialize UNIT
52 read c = Just (UNIT, c)
54 instance serialize (EITHER a b) | serialize a & serialize b
56 write (LEFT a) c = write a c
57 write (RIGHT a) c = write a c
58 read c = case read c of
59 Just (a, c) = Just (LEFT a, c)
60 Nothing = case read c of
61 Just (a, c) = Just (RIGHT a, c)
64 instance serialize (PAIR a b) | serialize a & serialize b
66 write (PAIR a b) c = write a (write b c)
67 read c = case read c of
68 Just (a, c) = case read c of
69 Just (b, c) = Just (PAIR a b, c)
73 instance serialize (CONS UNIT)
75 write (CONS n UNIT) c = [n:c]
76 read [n:c] = Just (CONS n a, c)
79 instance serialize (CONS a) | serialize a
82 | write a [] == [] = [n:c]
83 = ["(",n:write a [")":c]]
84 read ["(",n:c] = case read c of
85 Just (a, [")":c]) = Just (CONS n a, c)
87 read [n:c] = case read c of
88 Just (a, c) = Just (CONS n a, c)
92 Start :: (Maybe ([[Int]], [String]), [String])
93 Start = (read (write (fromList what) []), write (fromList what) [])
96 what = [[1,2],[1,2,3]]