---
--- 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.
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