【发布时间】:2015-05-05 12:26:34
【问题描述】:
我正在尝试在 Haskell 中创建一个程序,该程序从文本文件中读取文本并将它们添加到列表中。
我的想法是:
type x = [(String, Integer)]
其中 String 是文本中的每个单词,Integer 是该单词在文本中出现的次数。所以我想创建这些值的元组并将其添加到列表中。然后我想打印列表的内容。
我知道如何在 Haskell 中读取文本文件,但不确定下一步该做什么。我是 Haskell 编程的新手,主要是用 Java 编程,这是非常不同的。
编辑:
这就是我到目前为止的建议。我可以使用从文件中接收到的文本写入输出文本文件并将其设为小写。我遇到的问题是使用其他功能,因为它说:
Test.hs:14:59: Not in scope: ‘group’
代码如下:
import System.IO
import Data.Char(toLower)
main = do
contents <- readFile "testFile.txt"
let lowContents = map toLower contents
let outStr = countWords (lowContents)
let finalStr = sortOccurrences (outStr)
print outStr
-- Counts all the words
countWords :: String -> [(String, Int)]
countWords fileContents = countOccurrences (toWords fileContents)
-- Split words
toWords :: String -> [String]
toWords s = words s
-- Counts, how often each string in the given list appears
countOccurrences :: [String] -> [(String, Int)]
countOccurrences xs = map (\xs -> (head xs, length xs)) . group . sortOccurrences xs
-- Sort list in order of occurrences.
sortOccurrences :: [(String, Int)] -> [(String, Int)]
sortOccurrences sort = sortBy sort (comparing snd)
请任何人帮助我。
【问题讨论】:
-
您应该将问题分解为更小的步骤。然后你可能想使用
Data.Map。 -
首先请注意
x不是有效的类型名称(需要大写)-我认为这可能是家庭作业(如果不是,我很抱歉)所以我不想要剧透太多,但是 list 在这里不是一个很好的选择(因为你必须经常更新它)——也许看看maps——你也一定想到了什么- 一点头绪都没有? -
spoiler 如果地图太复杂,你可以改用
String -> Integer函数 - 你可以用addOccurence f word = \w -> if w == word then f w + 1 else f w更新它 我发现这更容易开始(请注意这可能不是很有效 - 但它很简单) - 也寻找 folds (foldr,foldl, ...) - 也许你可以以某种方式使用它们
标签: list haskell tuples readfile