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