user3645265
user3645265

Reputation: 783

List comprehension Haskell

I'm having problem with one exercise, where i need to use the list comprehension, the problem is something like this: I receive the list, and i have to count and return another list with the number of occurrences of each number o ( 0-5).

For example:

[3,3,2,0,3,4] the output should be [1,0,1,2,1,1], 
-number 0 only happens 1 time
-number 1 never occurs 
-numer 2 occurs 1 time 
-number 3 occurs 2 times 
-and so on

What i have tried:

nTimes = [ y| x<-[0..5], y<- (occurs x [3,3,2,0,3,4])]


occurs n [] = 0
occurs n (x:xs) | n == x = 1+ occurs ( n xs)
                | otherwise = occurs n xs

I think the problem is with my comprehension list. Can someone guide me to the solution?

Upvotes: 1

Views: 261

Answers (1)

marc
marc

Reputation: 6233

First of all, y is not a list, so you have to introduce it via let or use it in the body.

nTimes = [ y| x<-[0..5], let y = occurs x [3,3,2,0,3,4]]
-- or
nTimes = [ occurs x [3,3,2,0,3,4] | x<-[0..5]]

The function itself only has a minor mistake in its recursive call

occurs n [] = 0
occurs n (x:xs) | n == x = 1 + occurs n xs
                | otherwise = occurs n xs

or, a more fun way to write it

occurs n x = length $ filter (== n) x

Upvotes: 1

Related Questions