Haskell 福尔德问题(哈斯克尔)
我正在尝试从类型为Haskell 福尔德问题(哈斯克尔),haskell,fold,Haskell,Fold,我正在尝试从类型为([Char,Int])的表转换为字符串tab2str::table->string(遵循一些特定的格式模式) 我正在使用foldr(正如标题所暗示的),但在使确切的函数正常工作时,我遇到了一些问题,即It错误。我的函数如下所示: tab2str xs=foldr(++)''$map(\char count->show char++':'++show count++'\n')xs 输出应该是表中的每个字母,一个冒号,然后是\n。因此,测试可能是: tab2str test1=
([Char,Int])
的表转换为字符串tab2str::table->string
(遵循一些特定的格式模式)
我正在使用foldr(正如标题所暗示的),但在使确切的函数正常工作时,我遇到了一些问题,即It错误。我的函数如下所示:
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)]
感谢您的帮助。经过最少的更正后,此类型检查:
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>
经过最小限度的更正后,此类型检查:
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>
您可以通过使用concatMap和删除表来改进这一点paramter@Arjan我认为这不会提高可读性。但事实上,这将使代码缩短一点。您可以通过使用concatMap和删除表来改进这一点paramter@Arjan我认为这不会提高可读性。函数式编程提示:像这样使用
foldr
的代码通常很难阅读foldr
最好用于编写“中间”实用程序函数,然后用于解决具体问题。例如,map
、filter
、(++)
、concat
和许多其他标准列表函数都是foldr
。功能编程提示:像这样使用foldr
的代码通常很难阅读foldr
最好用于编写“中间”实用程序函数,然后用于解决具体问题。例如,map
、filter
、(++)
、concat
和许多其他标准列表函数都在引擎盖下。