Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the problem with my manually created length function in Haskell?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading