[Haskell-cafe] Suspected stupid Haskell Question

Peter Verswyvelen bf3 at telenet.be
Wed Oct 17 06:58:31 EDT 2007


I'm a newbie here, so I'm not sure about my reply, but I think this is 
not the answer to his question.

freq ["egg", "egg", "cheese"] indeed returns [2,1]

but

freq ["egg", "cheese", "egg"] returns [1,1,1]

BH just mentioned he needed the frequenty of elements in the list, 
independent of their order.

So in that case, the result should be a list of ordered pairs like: 
[("egg", 2), ("cheese", 1)]. Or a pair of two lists, like (["egg", 
"cheese"), (2,1)]. Otherwise you would not know which frequency belongs 
to which element?

I can't write this concisely nor efficient yet, but the following does 
the job:

import Data.List

freq xs = zip e f
  where
    s = sort xs
    e = nub s
    f = map length (group s)

However, I suspect the experts here will be able to make that much 
shorter and more efficient (maybe using Data.Map?)

Peter


Stefan Holdermans wrote:
> BH,
>
>> Is there a library function to take a list of Strings and return a 
>> list of
>> ints showing how many times each String occurs in the list.
>>
>> So for example:
>>
>> ["egg", "egg", "cheese"] would return [2,1]
>
> freq xs = map length (group xs)
>
> HTH,
>
>   Stefan
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>



More information about the Haskell-Cafe mailing list