I am trying to create a length function by myself in Haskell, but when I try to execute it with any type of the list, it says "non exhaustive patterns" What is the problem?
I tried "func [1] 0" and it was supposed to recursively call "func" once and then return y, because it is "func [] y = y". However, it gives me "non exhaustive patterns"
func list y = func (tail list) (y+1)
func [] y = y
Invert the order of the two equations. They are tried in order, and the first one matches any list
, including the empty list, so the second equation is never taken.
You should always turn warnings on. GHC warns about this specific mistake, pointing out that the second equation is never taken.
Also, if you use GHCi, be sure to write both equations in an .hs file and to :load
it in GHCi. If you instead enter both equations one after the other at GHCi prompt the second one will overwrite the first one (GHCi assumes you want to redefine the function with a new definition).