Calculating the length of an array in haskell
This question already has an answer here:
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>
链接地址: http://www.djcxy.com/p/43280.html
上一篇: 使用if的详尽模式
下一篇: 计算haskell中数组的长度