问题
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?
回答1:
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 using length
function
String -> [[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
to 100*(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)]
来源:https://stackoverflow.com/questions/19323958/string-letter-percentages-in-haskell