Calculating the length of an array in haskell - non exhaustive patterns error [duplicate]

≯℡__Kan透↙ 提交于 2019-12-01 08:42:18

问题


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


回答1:


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>


来源:https://stackoverflow.com/questions/19231915/calculating-the-length-of-an-array-in-haskell-non-exhaustive-patterns-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!