module serializenative import StdEnv, StdMaybe, StdGeneric class serialize a | read{|*|}, write{|*|} a generic write a :: a [String] -> [String] generic read a :: [String] -> Maybe (a, [String]) write{|Bool|} b c = [toString b:c] read{|Bool|} ["True":c] = Just (True, c) read{|Bool|} ["False":c] = Just (False, c) read{|Bool|} _ = Nothing write{|Int|} i c = [toString i:c] read{|Int|} [i:c] = Just (toInt i, c) read{|Int|} _ = Nothing write{|UNIT|} UNIT c = c read{|UNIT|} c = Just (UNIT, c) write{|EITHER|} wl _ (LEFT a) c = wl a c write{|EITHER|} _ wr (RIGHT a) c = wr a c read{|EITHER|} rl rr c = case rl c of Just (a, c) = Just (LEFT a, c) Nothing = case rr c of Just (a, c) = Just (RIGHT a, c) Nothing = Nothing write{|PAIR|} wl wr (PAIR l r) c = wl l (wr r c) read{|PAIR|} rl rr c = case rl c of Just (a, c) = case rr c of Just (b, c) = Just (PAIR a b, c) Nothing = Nothing Nothing = Nothing write{|CONS of {gcd_name}|} wa (CONS a) c = ["(",gcd_name:wa a [")":c]] read{|CONS|} ra ["(",n:c] = case ra c of Just (a, [")":c]) = Just (CONS a, c) _ = Nothing read{|CONS|} _ _ = Nothing write{|OBJECT|} wa (OBJECT a) c = wa a c read{|OBJECT|} ra c = case ra c of Just (a, c) = Just (OBJECT a, c) _ = Nothing :: Bin a = Leaf | Bin (Bin a) a (Bin a) instance == (Bin a) | == a where (==) Leaf Leaf = True (==) (Bin l a r) (Bin k b s) = l == k && a == b && r == s (==) _ _ = False :: Coin = Head | Tail instance == Coin where (==) Head Head = True (==) Tail Tail = True (==) _ _ = False derive class serialize Coin, Bin, (,), [] // output looks nice if compiled with "Basic Values Only" for console in project options Start = [test True ,test False ,test 0 ,test 123 ,test -36 ,test [42] ,test [0..4] ,test [[True],[]] ,test [[[1]],[[2],[3,4]],[[]]] ,test (Bin Leaf True Leaf) ,test [Bin (Bin Leaf [1] Leaf) [2] (Bin Leaf [3] (Bin Leaf [4,5] Leaf))] ,test [Bin (Bin Leaf [1] Leaf) [2] (Bin Leaf [3] (Bin (Bin Leaf [4,5] Leaf) [6,7] (Bin Leaf [8,9] Leaf)))] ,test Head ,test Tail ,test (7,True) ,test (Head,(7,[Tail])) ,["End of the tests.\n"] ] test :: a -> [String] | serialize, == a test a = (if (isJust r) (if (fst jr == a) (if (isEmpty (tl (snd jr))) ["Oke"] ["Not all input is consumed! ":snd jr]) ["Wrong result: ":write{|*|} (fst jr) []]) ["read result is Nothing"] ) ++ [", write produces: ": s] where s = write{|*|} a ["\n"] r = read{|*|} s jr = fromJust r