Haskell中的字符串字母百分比 [英] String letter percentages in Haskell
问题描述
我试着编写一个Haskell函数,它会接受一个字符串表示PLATYPUS并返回该字中字符的相对百分比,即characterPercentagesPLATYPUS将返回:[(P,25),(A, 13),(L,13),(S,13),(T,13),(U,13),(Y,13)]。我知道我可以使用元组,但之后我有点难住?
解决方案首先,您需要了解什么是你会得到。
据我所知,你希望有
type String = [Char] - 已经在Prelude中
String - > [(Char,Int)]
PLATYPUS - => [( 'P',2),( 'A',1),( 'L',1),( 'S',1),( 'T',1),( 'U',1),( 'Y',1)]
您可以结合 group
从 length 函数进行映射的数据列表
$ b
字符串 - > [[Char]]
[[Char]] - > [(Char,Int)]
已更新
如果我们谈论第一部分 - 数字信件,我们可以做下一步:
> :m Data.List
$ p $因此,让我们找到相对数字,我们将
> map(\c->(head c,length c))$ group $ sortPLATYPUSAAA
[('A',4),('L',1),('P',2 ),('S',1),('T',1),('U',1),('Y',1)]
长度c
更改为100 *(长度c) 'div'ls
:>让frqLetters s = let ls = length s in
map(\c - >(head c,100 *(length c)`div` ls))$ group $ sort s
> fr'LettersPLATYPUSAAA
[('A',36),('L',9),('P',18),('S',9),('T',9), 'U',9),('Y',9)]
I'm trying to write a Haskell function that will take a String say "PLATYPUS" and will return the relative percentages of Characters in that word i.e. characterPercentages "PLATYPUS" would return: [(P,25),(A,13),(L,13),(S,13),(T,13),(U,13),(Y,13)]. I know I can use tuples, but after that I'm a bit stumped?
解决方案First, you need to understand what are you going to get.
As I understand, you wish to have
type String = [Char] --already in Prelude String -> [(Char,Int)] "PLATYPUS" -=> [('P',2),('A',1),('L',1),('S',1),('T',1),('U',1),('Y',1)]
You could combine
group
grouping lists from Data-List with mapping usinglength
functionString -> [[Char]] [[Char]] -> [(Char,Int)]
UPDATED
If we talk about first part - count letters, we can do next:
> :m Data.List > map (\c -> (head c, length c)) $ group $ sort "PLATYPUSAAA" [('A',4),('L',1),('P',2),('S',1),('T',1),('U',1),('Y',1)]
So, let's found relative numbers, we change
length c
to100*(length c) 'div' ls
:> let frqLetters s = let ls = length s in map (\c -> (head c, 100 * (length c) `div` ls)) $ group $ sort s > frqLetters "PLATYPUSAAA" [('A',36),('L',9),('P',18),('S',9),('T',9),('U',9),('Y',9)]
这篇关于Haskell中的字符串字母百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!