Created
August 27, 2016 00:04
-
-
Save sortega/27f011a49d62305836d74bc2ba2bddeb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE FlexibleInstances, OverlappingInstances #-} | |
import Data.List | |
toJson1 :: [String] -> String | |
toJson1 elems = toArray $ map quote elems | |
where quote elem = '"' : elem ++ "\"" | |
toArray elems = '[' : concat (intersperse ", " elems) ++ "]" | |
sample1 = toJson1 ["a", "b", "c"] | |
toJson2 elems = toArray $ map show elems | |
where toArray elems = '[' : concat (intersperse ", " elems) ++ "]" | |
data Conversation = Conversation { from :: Int, to :: Int, text :: String } | |
deriving (Show) | |
-- instance Show Conversation where | |
-- show (Conversation from to text) = | |
-- concat [ "{\"from\":", show from, ",", | |
-- "\"to\":", show to, ",", | |
-- "\"text\":", show text, "}" ] | |
class EncodeJson a where | |
toJson :: a -> String | |
instance EncodeJson String where | |
toJson = show | |
instance EncodeJson Int where | |
toJson = show | |
instance EncodeJson Conversation where | |
toJson (Conversation from to text) = | |
concat [ "{\"from\":", show from, ",", | |
"\"to\":", show to, ",", | |
"\"text\":", show text, "}" ] | |
toJson3 :: EncodeJson a => [a] -> String | |
toJson3 elems = toArray $ map toJson elems | |
where toArray elems = '[' : concat (intersperse ", " elems) ++ "]" | |
instance EncodeJson a => EncodeJson [a] where | |
toJson elems = toArray $ map toJson elems | |
where toArray elems = '[' : concat (intersperse ", " elems) ++ "]" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment