I am trying to count the elements of a list that are the same length for n and n+1.
I wrote this code:
countSec :: [[Integer]] -> Integer
countSec (x:xs) = if (length x)==(length (head xs))
then 1+(countSec xs)
else (countSec xs)
countSec [] = 0
As you may guess, it’s not working. In fact, as a output I get “* Exception: Prelude.head: empty list”
countSec [[1,2][1,2],[2],[3,5],[2],[5]] should return 2 (the first two and the last two sublists have the same length).
Any clue on what the problem can be?
Thanks
You don’t handle the case where there is only one element in the list of lists, so you run into an error as soon as you call
headonxs, which will be[], since there’s no first element of an empty list 🙂You can use pattern matching to fix this:
I used pattern matching to match two elements of the list at a time. This is just like
x:(y:_)(patterns can nest), except that we also give the namexsto the thing we matched toy:_; so we havexis the first element of the list,yis the second, andxsis the list after the first element. We could just match(x:y:xs)instead and usecountSec (y:xs)to recurse, but this would use up more memory and is more error-prone.The
_in a pattern means that we don’t care about the value at that position, and so don’t want to give it a name; it’s a wildcard that matches everything.As a minor stylistic note, I also converted your
ifexpression into a guard; these are basically just if expressions at the level of a function clause.You should avoid using partial1 functions like
headwhen pattern matching would work because of things like this — they hide errors and make code harder to read. I also suggest giving the-Wallflag to GHC; if you wrotecountSecas I did but forgot the zero or one-element case, GHC would warn you about it:1 A function not defined for all its inputs; for instance,
headandtailare not defined on[], and division is not defined when the divisor is 0.