Skip to content

Instantly share code, notes, and snippets.

@sortega
Created August 27, 2016 00:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sortega/27f011a49d62305836d74bc2ba2bddeb to your computer and use it in GitHub Desktop.
Save sortega/27f011a49d62305836d74bc2ba2bddeb to your computer and use it in GitHub Desktop.
{-# 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