GHCi 中函数的非穷举模式 [英] Non exhaustive pattern in function in GHCi

查看:19
本文介绍了GHCi 中函数的非穷举模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个显示列表最后一个元素的函数.这是我的代码:

ghci>让 myLast :: [a] ->一种ghci>让 myLast [] = 错误ghci>让 myLast [x] = xghci>让 myLast (x:xs) = myLast xs

我收到以下错误:

<块引用>

***例外:函数 myLast 中的非穷尽模式

我知道您在丢失案例时会收到此错误,但我想我已经包含了所有可能性.有什么想法吗?

解决方案

如果你在每一行都使用了一个 let,那么每个定义都会产生一个名为 new 函数>myLast,隐藏所有以前的定义.所以你最终得到的相当于

<块引用>

GHCi> 让 myLast (x:xs) = myLast xs

一个人.

你可能想要的是制作一个haskell文件,比如MyLast.hs,包含

module MyLast wheremyLast :: [a] ->一种myLast [] = 错误myLast [x] = xmyLast (x:xs) = myLast xs

然后您可以使用 ghci MyLast.hs 将该文件加载到 GHCi 中.

关键字 let 仅当您已经在 GHCi 中(或者,在一些像 IO 这样的 monad 中,或在另一个函数中)并且想要创建一个 本地定义.但是你必须只使用 let 一次,例如

<块引用>

GHCi> 让 myLast :: [a]->a;myLast [] = 错误;myLast [x] = x;myLast (x:xs) = myLast xs

twiceLast :: [Int] ->[内部]doubleLast = 让 myLast [] = 错误myLast [x] = xmyLast (x:xs) = myLast xs在 xs ->2 * 最后一个 xs

然而,我更愿意写成

twiceLast = (2*) .我最后一次其中 myLast [] = 错误myLast [x] = xmyLast (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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆