1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
--- --- Tag --- data Tag = Tag { tagType :: String, tagAttrs :: [Attr] } data Attr = Attr String String --- --- tagToHTML --- tagToHTML :: Tag -> String tagToHTML t = "<" ++ tagType t ++ " " ++ attrs ++ "/>a" where attrs = join (map attrPair (tagAttrs t)) --- --- attrPair --- attrPair :: Attr -> String attrPair (Attr k v) = k ++ "=\"" ++ v ++ "\"" --- --- join --- join :: [String] -> String join (x:xs) = x ++ " " ++ (join xs) join [] = "" --- main input = Tag "input" [Attr "id" "comments", Attr "disabled" "disabled"] main = print (tagToHTML input)
Refactorings
No refactoring yet !
sargon
April 13, 2009, April 13, 2009 09:51, permalink
Using show instances for printing operations make outputing data more transparent.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
data Tag = Tag { tagType :: String, tagAttrs :: [Attr] } data Attr = Attr String String instance Show Tag where show tag = foldr (++) "" ["<",tagType tag," ",unwords.(map show) $ tagAttrs tag,"/>"] instance Show Attr where show (Attr k v) = concat [k,"=\"",v,"\""] input = Tag "input" [Attr "id" "comments", Attr "disabled" "disabled"] main = print input
sargon
April 13, 2009, April 13, 2009 09:54, permalink
arg,
in the instance of Show Tag using concat instead of foldr will do the job with less chars ;)
Tj Holowaychuk
April 13, 2009, April 13, 2009 15:13, permalink
Ah I was wondering what this Show stuff was about, had a feeling there was a much better way to do that. thanks!
Just playing around, super new to Haskell (1 hour or so), and pointers would be great