在之前看到一篇关于文本文件索引的帖子后,我开始好奇,因为我目前正在学习使用 Haskell(进展不顺利)是否有可能在 Haskell 中轻松实现相同的目标: How do I create a Java string from the contents of a file?
该类(class)的目标是读取文件,按字母顺序排列文件中的单词并显示这些单词出现的行号。
Haskell 中的函数可以用类似的方法构建吗?
最佳答案
这是一个 Haskell 解决方案
import Data.List (sortBy)
import Data.Function (on)
numberWordsSorted :: String -> [(String,Int)]
numberWordsSorted = sortBy (compare `on` fst)
. concat
. zipWith (\n xs -> [(x,n)|x<- xs]) [1..] -- add line numbers
. map words
. lines
main = fmap numberWordsSorted (readFile "example.txt") >>= mapM_ print
如果您在包含内容的example.txt
上运行它
the quick brown fox
jumps over the lazy dog
你得到
("brown",1)
("dog",2)
("fox",1)
("jumps",2)
("lazy",2)
("over",2)
("quick",1)
("the",1)
("the",2)
如果您更愿意看到 [1,2]
而不是两行输出,您应该使用 Data.Map
而不是 pairs。
关于java - Haskell 完整的文本文件索引器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23522156/