haskell - 使用折叠的字符串排序
问题描述
我是haskell的新手,开始写我的第一个小程序。
目的:应用程序要求用户输入某些类别的项目。所有输入都存储在地图类别 [项目](或地图字符串 [字符串])中。完成所有类别后,将地图写入文件。
import qualified Data.Map as Map
type InputLine = IO [String]
type ItemsRegistry = Map.Map String InputLine
--main = do sequence . printValues . getInput $ ["head", "body"]
main = do
writeFile "data.txt" ""
putStrLn "Write the word \"stop\" to end the input"
sequence . writeData "data.txt" . getInput $ ["B", "A"]
getInput :: [String] -> ItemsRegistry
getInput cat = foldl (\acc category -> Map.insert category (insertCategory category) acc) Map.empty cat
insertCategory :: String -> InputLine
insertCategory category = do
putStrLn $ "Add items for category " ++ category
insertItem []
insertItem :: [String] -> InputLine
insertItem values = do
x <- getLine
case x of "stop" -> return values
x -> insertItem (x:values)
writeData :: String -> ItemsRegistry -> [IO ()]
writeData path data_ = [ writeLine path k (Map.lookup k data_) | k <- Map.keys data_ ]
-- filepath category lineOfItems
writeLine :: String -> String -> Maybe InputLine -> IO ()
writeLine path category (Just line) = line >>= (\words -> appendFile path $ formatLine category (unwords words))
writeLine path category Nothing = return ()
formatLine :: String -> String -> String
formatLine category items = category ++ " " ++ items ++ "\n"
--printValues :: ItemsRegistry -> [IO ()]
--printValues l = [ v >>= putStrLn . show | (k,v) <- Map.toList l]
运行上述内容时,我不知道为什么它在 B 之前要求我输入类别 A ,因为我使用了 foldl ?似乎它背后有一些词汇顺序,但我不明白为什么。
谢谢
解决方案
根据Data.Map 的文档,返回Map.keys
“按升序排列的地图的所有键”。(回想一下,该Map
类型要求其键是 的实例的类型Ord
。)
由于按自然顺序"A"
出现在前面,我认为您的使用导致在“请求 B”之前有“请求 A”动作。"B"
Map.keys
writeData
推荐阅读
- android - AlertDialog 中的 EditText 不会自动聚焦于 Android 9 (API 28)
- php - 我在 PHP 包含变量时遇到 include failed to open stream 错误
- c# - c# 广度优先搜索在迷宫中查找项目
- sidr - 用户单击链接时关闭 sidr 菜单
- c# - 当 Parallel.For 尚未完成时,如何处理 WM_PAINT?
- c# - 无法订阅节点 RosSharp C# Unity
- javascript - 为什么 setTimeout 返回数值
- r - 将新列添加到数据框中,它是 for 循环 R 中数据框的名称?
- java - Minecraft - 物品栏上方的信息栏完全人工制作
- formatting - 如何格式化数字向量和字符串向量?(Dyalog APL)