Reputation: 1719
I'm trying to convert from a table which is of type ([Char, Int])
to a string tab2str :: Table -> String
(that follows some specific formatting patterns.)
I'm using foldr (as the title implies) but I'm having some issues getting the exact function to work - i.e. It errors. My function looks like this:
tab2str xs = foldr (++) ' ' $ map (\char count -> show char ++ ':' ++ show count ++ '\n') xs
The output should be each letter in the table, a colon, then \n
. So a test might be:
tab2str test1 == "F: 1\no: 1\nl: 1\nd: 1\nr: 1\n"
where
test1 == [(F, 1), (o, 1), (l, 1), (d, 1), (r, 1)]
Any help gratefully received.
Upvotes: 1
Views: 265
Reputation: 15652
After minimal corrections this typechecks:
tab2str xs = foldr (++) " " $ map (\(char, count) -> show char ++ ":" ++ show count ++ "\n") xs
– but produces not quite what you want.
You'll probably like this better:
tab2str table = concat $ map formatRow table
where formatRow (char, count) = [char] ++ ": " ++ show count ++ "\n"
Then your test example:
ghci> let test1 = [('F', 1), ('o', 1), ('l', 1), ('d', 1), ('r', 1)]
ghci> tab2str test1
"F: 1\no: 1\nl: 1\nd: 1\nr: 1\n"
ghci> putStr $ tab2str test1
F: 1
o: 1
l: 1
d: 1
r: 1
ghci>
Upvotes: 1