I try to write a program which will count the frequency of each element in a list.
In: "aabbcabb"
Out: [("a",3),("b",4),("c",1)]
You can view my code in the following link: http://codepad.org/nyIECIT2
In this code the output of unique function would be like this
In: "aabbcabb"
Out: "abc"
Using the output of unique we wil count the frequency of the target list.
You can see the code here also:
frequencyOfElt xs=ans
where ans=countElt(unique xs) xs
unique []=[]
unique xs=(head xs):(unique (filter((/=)(head xs))xs))
countElt ref target=ans'
where ans'=zip ref lengths
lengths=map length $ zipWith($)(map[(=='a'),(==',b'),(==',c')](filter.(==))ref)(repeat target)
Error:Syntax error in input (unexpected symbol "unique")
But in ghci 6.13 other type of error are showing also
Few asked me what is the purpose of using [(==’a’),(==’,b’),(==’,c’)].
What I expect: If ref=”abc” and target=”aabbaacc”
then
zipWith($) (map filter ref)(repeat target)
will show [“aaaa”,”bb”,”cc”] then I can use map length over this to get the frequency
Here for filtering list according with the ref i use [(==’a’),(==’,b’),(==’,c’)]
I assume some logical error lies [(==’a’),(==’,b’),(==’,c’)] here..
You didn’t say whether you want to write it whole on your own, or whether it’s OK to compose it from some standard functions.
is the standard quick-n-dirty way to code it.
OK, so your original idea was to Code it Point-Free Style (certain tune playing in my head…):
I’ve changed the type here to the more reasonable
[a] -> [(a,Int)]btw. Note, thathence the code simplifies to
and then
but
map f $ map g xs === map (f.g) xs, sowhich is a bit clearer (for my taste) written with a list comprehension,
Which gives us an idea to re-write (1) further as
but this obsession with point-free code becomes pointless here.
So going back to the readable list comprehensions, using a standard
nubfunction which is equivalent to yourunique, your idea becomesThis algorithm is actually quadratic (
~ n^2), so it is worse than the first version above which is dominated bysorti.e. is linearithmic (~ n log(n)).This code though can be manipulated further by a principle of equivalent transformations:
… because searching in a list is the same as searching in a list, sorted. Doing more work here — will it pay off?..
… right? But now,
grouphad already grouped them by(==), so there’s no need for thefiltercall to repeat the work already done bygroup:isn’t it? And here it is, the same linearithmic algorithm from the beginning of this post, actually derived from your code by factoring out its hidden common computations, making them available for reuse and code simplification.