您拥有的是两个声明,其中第二个影响了第一个。
您需要声明len
为一个带有两个子句的函数。在 GHCi 中,您可以这样做:
:{
let len [] = 0
len (h:t) = 1 + len t
:}
该:{ ... :}
表单允许您像在*.hs
文件中一样输入多行声明。
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>