首页 > 解决方案 > 使用折叠的字符串排序

问题描述

我是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 ?似乎它背后有一些词汇顺序,但我不明白为什么。

谢谢

标签: haskell

解决方案


根据Data.Map 的文档,返回Map.keys“按升序排列的地图的所有键”。(回想一下,该Map类型要求其键是 的实例的类型Ord。)

由于按自然顺序"A"出现在前面,我认为您的使用导致在“请求 B”之前有“请求 A”动作。"B"Map.keyswriteData


推荐阅读