gpt4 book ai didi

list - Haskell 中的字数统计

转载 作者:行者123 更新时间:2023-12-04 00:53:03 25 4
gpt4 key购买 nike

我正在尝试计算数量文本中每个单词的出现次数然后将其表示为元组列表。

我尝试过使用累加器我尝试使用 concat和过滤器。发生了什么问题是我不确定如何处理列表中的列表。

我不确定如何从这里继续,我尝试在参数上使用过滤器 (x/=) 来调用函数 wordCountt,但由于某种原因该函数无法运行。非常感谢这里的一些指导。

干杯

type Document = [Sentence]
type WordTally = [(String, Int)]

wordCountt :: Document -> WordTally
wordCountt [] = []
wordCountt [(x:xs), ys] = [(x, length (filter (x ==) (concat [(x:xs), ys])))] ++ wordCountt [xs, ys]```



```wordCountt [["a", "rose", "is", "a", "rose"],["but", "so", "is", "a", "rose"]]
[("a",3),("rose",3),("is",2),("a",2),("rose",2)*** Exception: CompLing.hs:(60,1)-(61,100): Non-exhaustive patterns in function wordCountt```

最佳答案

对于制作直方图,我一直喜欢 Map.fromListWith :

import qualified Data.Map.Strict as Map
import Data.Map (Map)

histogram :: Ord a => [a] -> Map a Int
histogram xs = Map.fromListWith (+) (zip xs (repeat 1))

它的工作原理:

> zip (words "a rose is a rose") (repeat 1)
[("a",1),("rose",1),("is",1),("a",1),("rose",1)]

> Map.fromListWith (+) [("hello",1),("hello",1)]
fromList [("hello",2)]

> Map.fromListWith (+) [("a",1),("rose",1),("is",1),("a",1),("rose",1)]
fromList [("a",2),("is",1),("rose",2)]

> histogram (words "a rose is a rose")
fromList [("a",2),("is",1),("rose",2)]

因此,当同一个单词出现在两个(单词、计数)元组中时,计数将变为“+”。

关于list - Haskell 中的字数统计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64899245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com