Question

I've searched around on here and on the net in general and I can't find anything that seems to be answering this question. I've only just starting playing around with Haskell for a module at university and I'm having an issue defining a function to calculate the length of an array (the pre-existing length function essentially).

In my lecture notes the function is given as:

let len [] = 0
let len (h:t) = 1 + len t

This makes sense to me, it doesn't seem to be missing anything and I've seen something very similar posted elsewhere as well, but in GHCi it's throwing a "Non-exhaustive patterns" error and I can't for the life of me figure out why.

Any help would be much appreciated, thanks

Was it helpful?

Solution

What you have is two declarations, the second of which shadows the first.

You need to declare len as one function with two clauses. In GHCi, you can do that like this:

:{
let len [] = 0
    len (h:t) = 1 + len t
:}

the :{ ... :} form lets you enter multi-line declarations as you would in a *.hs file.

GHCi, version 7.6.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.

Prelude> let len [] = 0
Prelude> let len (h:t) = 1 + len t -- this shadows the earlier len
Prelude> len [1, 2, 3]
*** Exception: <interactive>:3:5-25: Non-exhaustive patterns in function len 
    -- exception because the new len doesn't handle an empty list

Prelude> :{
Prelude| let len [] = 0
Prelude|     len (h:t) = 1 + len t
Prelude| :}
Prelude> len [1, 2, 3]
3
Prelude>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top