实现空函数 [英] Implementation of null function

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

问题描述

我必须学习Haskell的大学,因此我开始时使用learnyouahaskell.com。我一直使用命令式语言,所以我决定通过编码比其他语言编码更多。
我开始执行几个函数来处理头, tail init ,...

在某些时候,我查找了这些函数的实现来与我的进行比较,并且偶然发现了<$ c中定义的空函数$ c $> List.lhs



null的执行:

   -  |测试列表是否为空。 
null :: [a] - > Bool
null [] = True
null(_:_)= False

我的执行:

  mNull :: [a]  - > Bool 
mNull [] = True
mNull _ = False

我知道那里即使对于这样简单的问题也不是愚蠢的问题:)

所以我的问题是为什么原始实现使用(_:_)而不是 _

使用(_:_)还是有优势吗?我不知道?

我无法真正想象任何优势,因为 _ 可以捕捉所有东西。



  mNull':: [a]  - > Bool 
mNull'_ = False
mNull'[] = True

this即使您传递一个空列表,
也会始终产生 False 。因为运行时没有考虑 [] 子句,它立即看到 _ 匹配任何内容。 (GHC会警告你这种重叠的模式)。另一方面,

 

null':: [a] - > Bool
null'(_:_)= False
null'[] = True

仍能正常工作,因为(_:_)无法匹配空列表的特定情况。



<这本身并没有真正给这两个明确的条款带来好处。但是,在更复杂的代码中,写出所有相互排斥的选项有一个好处:如果您忘记了一个选项,编译器也可以提醒您!而 _ 可以并且只会处理前面的子句没有处理的任何情况,即使这并不正确。


I have to learn Haskell for university and therefor I'm using learnyouahaskell.com for the beginning.
I always used imperative languages so I decided to practice Haskell by coding a lot more than I would for other languages.
I started to implement several functions to work with lists such as head, tail, init,...
At some point I looked up the implementations of these functions to compare to mine and I stumbled upon the null function defined in List.lhs.

null's implementation:

-- | Test whether a list is empty.
null                    :: [a] -> Bool
null []                 =  True
null (_:_)              =  False

my implementation:

mNull :: [a] -> Bool
mNull []        = True
mNull _         = False

I know there are no stupid questions even for such simple questions :)
So my question is why the original implementation uses (_:_) instead of just _?
Is there any advantage in using (_:_) or are there any edge cases I don't know of?
I can't really imagine any advantage because _ catches everything.

解决方案

You can't just turn the clauses around with your solution:

mNull' :: [a] -> Bool
mNull' _  = False
mNull' [] = True

this will always yield False, even if you pass an empty list. Because the runtime doesn't ever consider the [] clause, it immediately sees _ matches anything. (GHC will warn you about such an overlapping pattern.)

On the other hand,

null' :: [a] -> Bool
null' (_:_) = False
null' []    = True

still works correctly, because (_:_) fails to match the particular case of an empty list.

That in itself doesn't really give the two explicit clauses an advantage. However, in more complicated code, writing out all the mutually excluse options has one benefit: if you've forgotten one option, the compiler can also warn you about that! Whereas a _ can and will just handle any case not dealt with by the previous clauses, even if that's not actually correct.

这篇关于实现空函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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