GHCi中功能的非穷举模式 [英] Non exhaustive pattern in function in GHCi
问题描述
我想创建一个显示列表的最后一个元素的函数。
这是我的代码:
ghci> let myLast :: [a] - > a
ghci> let myLast [] =错误
ghci> let myLast [x] = x
ghci>让myLast(x:xs)= myLast xs
我得到以下错误:
$ b
***例外:函数myLast中的非详尽模式
我明白,如果您错过了某个案例,您会收到此错误消息,但我想我已经包含了所有可能性。任何想法?
如果您在每一行中使用 let
每个定义都会创建一个名为 myLast
的新函数,并映射所有以前的定义。所以你最终得到的结果是相当于
GHCi> let myLast(x:xs)= myLast xs
单独。
您可能需要的是制作一个haskell文件,比如 MyLast.hs
,包含
模块MyLast其中
myLast: :[a] - > a
myLast [] =错误
myLast [x] = x
myLast(x:xs)= myLast xs
然后,您可以使用 ghci MyLast.hs
将该文件加载到GHCi中。
关键字 let
只有在您已经在GHCi中时才需要(或者在 IO 或者在另一个函数中),并且想要创建一个本地定义。但是你只能使用
let
一次,例如
GHCi> let myLast :: [a] - > a; myLast [] =错误; myLast [x] = x; myLast(x:xs)= myLast xs
或
twiceLast :: [Int] - > [Int]
twiceLast = let myLast [] =错误
myLast [x] = x
myLast(x:xs)= myLast xs $ b $ in \xs - > 2 *最后xs
然而,我会喜欢写成
twiceLast =(2 *)。 myLast
其中myLast [] =错误
myLast [x] = x
myLast(x:xs)= myLast xs
I want to make a function that displays the last element of a list. This is my code:
ghci> let myLast :: [a] -> a
ghci> let myLast [] = error
ghci> let myLast [x] = x
ghci> let myLast (x:xs) = myLast xs
And I get the following error:
***Exception: Non-exhaustive patterns in function myLast
I understood that you get this error when you're missing a case, but I think I have included all the possibilities. Any ideas?
If you use a let
in each line, each definition will make a new function named myLast
, shadowing all the previous definitions. So what you end up with is equivalent to
GHCi> let myLast (x:xs) = myLast xs
alone.
What you probably want is to make a haskell file, say MyLast.hs
, containing
module MyLast where
myLast :: [a] -> a
myLast [] = error
myLast [x] = x
myLast (x:xs) = myLast xs
you can then load that file into GHCi with ghci MyLast.hs
.
The keyword let
is only needed when you're already in GHCi (or, in some monad like IO
, or in another function) and want to make a local definition. But then you must only use the let
once, e.g.
GHCi> let myLast :: [a]->a; myLast [] = error; myLast [x] = x; myLast (x:xs) = myLast xs
or
twiceLast :: [Int] -> [Int]
twiceLast = let myLast [] = error
myLast [x] = x
myLast (x:xs) = myLast xs
in \xs -> 2 * last xs
which I would, however, prefer to write as
twiceLast = (2*) . myLast
where myLast [] = error
myLast [x] = x
myLast (x:xs) = myLast xs
这篇关于GHCi中功能的非穷举模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!