I'm pretty new to Haskell and I am trying to define my own length function as follows:
lengthz :: [a] -> a
lengthz [] = 0
lengthz n = 1 + length (tail n)
Why does this not compile? And or, is there something wrong with my logic?
Thanks!
First, you have a typo in your recursive call to lengthZ. Fixing this, we encounter a new type error:
No instance for (Num a)
What this tells us is that in order to use the function (+), we must include the typeclass Num as a constraint in our type declaration. We also include a different type variable for the elements of the list so that the function can be applied to lists containing elements of any type. We thus rewrite the function as follows:
lengthz :: Num b => [a] -> b
lengthz [] = 0
lengthz n = 1 + lengthz (tail n)
Which works just as we'd expect:
ghci>> lengthz [1,2,3]
3
ghci>> lengthz []
0
The type for your lengthz function is [a] -> a.
This means you're taking a list of a things and returning a single a thing. What if you had a list of Bool? You don't want the function to output a Bool. You want an Int to be returned, regardless of the type of the thing in the list.
The simplest fix would be to change the type of lengthz to [a] -> Int. This says that the argument can be a list of anything (a is the anything, [] says it's a list) and the return type is an Int.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With