F1e3ab214a976a39cfd713bc93deb10f

Just playing around, super new to Haskell (1 hour or so), and pointers would be great

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

55ca8e1248605bf5e1819ce2c47c160f

sargon

April 13, 2009, April 13, 2009 09:51, permalink

2 ratings. Login to rate!

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
D41d8cd98f00b204e9800998ecf8427e

sargon

April 13, 2009, April 13, 2009 09:54, permalink

No rating. Login to rate!

arg,
in the instance of Show Tag using concat instead of foldr will do the job with less chars ;)

F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

April 13, 2009, April 13, 2009 15:13, permalink

No rating. Login to rate!

Ah I was wondering what this Show stuff was about, had a feeling there was a much better way to do that. thanks!

Your refactoring





Format Copy from initial code

or Cancel