3 import StdEnv, StdMaybe, StdGeneric
5 class serialize a | read{|*|}, write{|*|} a
7 generic write a :: a [String] -> [String]
8 generic read a :: [String] -> Maybe (a, [String])
10 write{|Bool|} b c = [toString b:c]
11 read{|Bool|} ["True":c] = Just (True, c)
12 read{|Bool|} ["False":c] = Just (False, c)
13 read{|Bool|} _ = Nothing
15 write{|Int|} i c = [toString i:c]
16 read{|Int|} [i:c] = Just (toInt i, c)
17 read{|Int|} _ = Nothing
19 write{|UNIT|} UNIT c = c
20 read{|UNIT|} c = Just (UNIT, c)
22 write{|EITHER|} wl _ (LEFT a) c = wl a c
23 write{|EITHER|} _ wr (RIGHT a) c = wr a c
24 read{|EITHER|} rl rr c = case rl c of
25 Just (a, c) = Just (LEFT a, c)
26 Nothing = case rr c of
27 Just (a, c) = Just (RIGHT a, c)
30 write{|PAIR|} wl wr (PAIR l r) c = wl l (wr r c)
31 read{|PAIR|} rl rr c = case rl c of
32 Just (a, c) = case rr c of
33 Just (b, c) = Just (PAIR a b, c)
37 write{|CONS of {gcd_name}|} wa (CONS a) c = ["(",gcd_name:wa a [")":c]]
38 read{|CONS|} ra ["(",n:c] = case ra c of
39 Just (a, [")":c]) = Just (CONS a, c)
41 read{|CONS|} _ _ = Nothing
43 write{|OBJECT|} wa (OBJECT a) c = wa a c
44 read{|OBJECT|} ra c = case ra c of
45 Just (a, c) = Just (OBJECT a, c)
48 :: Bin a = Leaf | Bin (Bin a) a (Bin a)
50 instance == (Bin a) | == a where
52 (==) (Bin l a r) (Bin k b s) = l == k && a == b && r == s
57 instance == Coin where
62 derive class serialize Coin, Bin, (,), []
64 // output looks nice if compiled with "Basic Values Only" for console in project options
74 ,test [[[1]],[[2],[3,4]],[[]]]
75 ,test (Bin Leaf True Leaf)
76 ,test [Bin (Bin Leaf [1] Leaf) [2] (Bin Leaf [3] (Bin Leaf [4,5] Leaf))]
77 ,test [Bin (Bin Leaf [1] Leaf) [2] (Bin Leaf [3] (Bin (Bin Leaf [4,5] Leaf) [6,7] (Bin Leaf [8,9] Leaf)))]
81 ,test (Head,(7,[Tail]))
82 ,["End of the tests.\n"]
85 test :: a -> [String] | serialize, == a
89 (if (isEmpty (tl (snd jr)))
91 ["Not all input is consumed! ":snd jr])
92 ["Wrong result: ":write{|*|} (fst jr) []])
93 ["read result is Nothing"]
94 ) ++ [", write produces: ": s]
96 s = write{|*|} a ["\n"]