2013-03-20 67 views
1

我试图从一个表,该表是([Char, Int])类型为字符串tab2str :: Table -> String(遵循一些特定格式的模式。)FOLDR问题(哈斯克尔)

我用foldr转换(如标题暗示)但我有一些问题得到确切的功能工作 - 即它的错误。我的功能看起来是这样的:

tab2str xs = foldr (++) ' ' $ map (\char count -> show char ++ ':' ++ show count ++ '\n') xs

输出应该在表中的每个字母,一个冒号,然后\n。因此,测试可能是:

tab2str test1 == "F: 1\no: 1\nl: 1\nd: 1\nr: 1\n"

其中 test1 == [(F, 1), (o, 1), (l, 1), (d, 1), (r, 1)]

任何帮助感激地接受。

+0

函数式编程提示:代码,使用'这样foldr'往往是难以阅读。 'foldr'最好用于编写“中间”实用函数,然后用它来解决具体问题。例如,'map','filter','(++)','concat'和其他许多标准列表函数全都是'foldr'。 – 2013-03-21 17:31:07

回答

1

最小修正后此typechecks:

tab2str xs = foldr (++) " " $ map (\(char, count) -> show char ++ ":" ++ show count ++ "\n") xs 

- 但会产生不太你想要什么。

你可能会喜欢这更好:

tab2str table = concat $ map formatRow table 
    where formatRow (char, count) = [char] ++ ": " ++ show count ++ "\n" 

然后测试例如:

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> 
+1

你可以通过使用concatMap和删除表参数来改善这个问题 – Arjan 2013-03-20 23:27:59

+0

@Arjan我不认为这会提高可读性。但的确,这会使代码缩短一点。 – ulidtko 2013-03-21 11:45:44