2 Replies - 624 Views - Last Post: 01 May 2011 - 10:18 AM

#1 darek9576   User is offline

  • D.I.C Lover

Reputation: 203
  • View blog
  • Posts: 1,731
  • Joined: 13-March 10

Counting occurences in Haskell.

Posted 01 May 2011 - 10:05 AM

So im trying to create a function that counts how many times the thing occurs in the list provided. Thats as far as i got:

occurences :: (Eq a, Num B)/> => a -> [a] -> b
occurences _ [] = error "The list is empty"
occurences x xs = sum [1 | y <- xs, x == y]




The above function does work but i was wondering whether you can do the same thing using guards.
Here is my second attempt (not complete, does not work)

occurences :: (Eq a, Num B)/> => a -> [a] -> b
occurences _ [] = error "The list is empty"
occurences x (y:ys)
               | x==y    = "increment the variable" AND occurences x ys
               | otherwise occurences x ys




Is it possible to do it using guards? In this case i would have to increment a variable and return it but i do not know whether its possible in Haskell.

Is This A Good Question/Topic? 0
  • +

Replies To: Counting occurences in Haskell.

#2 Raynes   User is offline

  • D.I.C Lover
  • member icon

Reputation: 614
  • View blog
  • Posts: 2,815
  • Joined: 05-January 09

Re: Counting occurences in Haskell.

Posted 01 May 2011 - 10:15 AM

occurences :: String -> [String] -> Int
occurences _ [] = 0
occurences x (y:ys)
  | x==y      = 1 + occurences x ys
  | otherwise = occurences x ys



I've changed the type because you didn't post B. Just change the type back around and it should work fine.

This is a very common and simple recursive algorithm. It might take a bit to wrap your head around it. Whenever x is equal to y, we add 1 to the result of calling occurences on the rest of the list. This happens over and over again, accumulating a number, until eventually the list is empty.
Was This Post Helpful? 2
  • +
  • -

#3 darek9576   User is offline

  • D.I.C Lover

Reputation: 203
  • View blog
  • Posts: 1,731
  • Joined: 13-March 10

Re: Counting occurences in Haskell.

Posted 01 May 2011 - 10:18 AM

Oh yeah. I knew it was simple enough. Yeah. I understand. The most confusing thing was how would i return/increment the value of occurences. But that makes perfect sense. Thanks. You rock.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1