Skip to main content
 首页 » 编程设计

list中haskell 列出字符频率

2024年12月31日57傻小

我在做作业时遇到问题!

编写函数

freq2 :: String -> -> [(Int,[Char])] 

freq一样,函数freq2计算字母字符出现的频率。

给定字符串:

我们认为这些真理是不言而喻的,即人人生而平等,造物主赋予他们某些不可剥夺的权利,其中包括生命权、自由权和追求幸福的权利

我需要结束:

[(1,"qv"), (2,"gm"), (3,"cfpwy"), (4,"b"), (5,"u"), (6,"do"),(8,"s"), (9,"ln"), (10,"i"), (12,"r"), (13,"h"), (16,"a"),(22,"t"), (28,"e")] 

到目前为止我可以到达:

[('q',1),('v',1),('g',2),('m',2),('c',3),('f',3),('p',3),('w',3),('y',3),('b',4),('u',5),('d',6),('o',6),('s',8),('l',9),('n',9),('i',10),('r',12),('h',13),('a',16),('t',22),('e',28)] 

使用:

 freq2 :: String -> [(Char,Int)] 
 freq2 input = result2 
    where 
    lower_case_list = L.map C.toLower input 
    filtered_list = L.filter C.isAlpha lower_case_list 
    result = L.map (\a -> (L.head a, L.length a)) $ L.group $ sort filtered_list 
    result2 = sortBy (compare `on` snd) result 

是否有一种简单的方法可以使用库函数进入最后阶段或完成整个过程?或者您能否提供一些关于如何完成这个问题的指导?

谢谢

请您参考如下方法:

附加到您的解决方案中的类似内容应该有效:

result3 = map (\xs@((_,x):_) -> (x,  map fst xs)) $ L.groupBy ((==) `on` snd) result2 

不过,我更喜欢使用 map 来解决这些类型的问题:

import qualified Data.Map as Map 
import qualified Data.Char as C 
import qualified Data.Tuple as T 
 
string = filter C.isAlpha $ map C.toLower "We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty and the pursuit of Happiness" 
 
swapMapWith f = Map.fromListWith f . map T.swap . Map.toList 
 
freq2 :: String -> [(Int, String)] 
freq2 = Map.toList . swapMapWith (++) . foldl (\agg c -> Map.insertWith (+) [c] 1 agg) Map.empty