Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - counting the number of occurrences of a value in a list

Tags:

haskell

So still working through Haskell tutorial...

One problem posed, is to write a function using:

count :: Eq a => [a] -> a -> Int

That can take a list of numbers & a value, and tell you how many times the value you specify occurs in the list.

It says to see if you can write it using List Comprehension, and again using Explicit Recursion...

AND, to use it to not just count occurrences of numbers -- but of letters, for instance, how many times does 's' occur in 'she sells sea shells'.

So I got:

countListComp :: Eq a => [a] -> a -> Int 
countListComp [] find = 0
countListComp ys find = length xs
    where xs = [xs | xs <- ys, xs == find]

and:

countRecursion :: Eq a => [a] -> a -> Int
countRecursion [] find = 0
countRecursion (x:xs) find 
    | find == x = 1 + (countRecursion xs find)
    | otherwise = countRecursion xs find

So it's counting the occurrences of numbers in a list just fine, like so:

ghci > countListComp [1,3,2,3,4,3] 3
3

ghci > countRecursion [6,9,7,9,8,9] 9
3

but when i look for a specific letter, it does this:

ghci > countListComp ["she sells sea shells"] "s"
0

ghci > countRecursion ["she sells sea shells"] "s"
0

it also said to try to count something else 'countable', like how many lists are there... so I tried:

ghci > countListComp [[1,2,3],[3,2,1],[4,5,6]] []
0

is there something wrong with my code, or am I not specifying what to look for correctly? I'm thinking it's the latter... because the following works:

For example, looking for how many times 's' occurs in 'she sells sea shells'... do I really have to put each individual letter in quotes with a comma between?? Like:

ghci > countRecursion ['s','h','e',' ','s','e','l','l','s',' ','s','e','a',' ','s','h','e','l','l','s'] 's'
6

And do I have to look for a specific list? Or is there a way to look for just a list with anything in it?

like image 463
Stormy Avatar asked Nov 16 '18 07:11

Stormy


2 Answers

Problem with countListComp ["she sells sea shells"] "s" is you have list of string.

You probably mean countListComp "she sells sea shells" 's'

Sting is just alias to list of character.

With countListComp [[1,2,3],[3,2,1],[4,5,6]] [] is different problem. It doesn't count how many list you have. It count how many list equals to [] you have.

If you try countListComp [[1,2,3],[],[4,5,6]] [] or countListComp [[1,2,3],[3,2,1],[4,5,6]] [3,2,1] you get 1.

like image 51
talex Avatar answered Oct 24 '22 05:10

talex


Try seeing what the first item in "she sells sea shells" is:

ghci> head "she sells sea shells"
=> 's'

's' is a Char, while "s" is a single-item [Char].

like image 3
amalloy Avatar answered Oct 24 '22 05:10

amalloy