null而不是== [英] null instead of ==

查看:129
本文介绍了null而不是==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习Haskell的兴趣。我按照 learnyouahaskell.com

I have just started to learn Haskell out of interest. I follow learnyouahaskell.com.

我发现这里:


null 检查列表是否为空。如果
是,它返回 True ,否则
返回 False 。使用此函数
而不是 xs == [] (如果你有一个
列表 xs

null checks if a list is empty. If it is, it returns True, otherwise it returns False. Use this function instead of xs == [] (if you have a list called xs)

为什么?当两者产生相同的结果时,为什么我们应该使用 null 而不是 ==

Why is that? Why should we use null instead of == when both produce the same result?

感谢。

推荐答案

将列表与 == 需要元素是可比的(表示为 Eq a )。

Comparing the lists with == requires elements to be comparable (denoted as Eq a).

Prelude> :t (==[])
(==[]) :: (Eq a) => [a] -> Bool

例如, [sin] == [] 将不工作,因为你不能比较函数。它可能看起来很蠢,但是类型系统必须判断一个表达式的类型而不用看它的值。

For example, [sin] == [] won't work, since you can't compare functions. It might seem stupid, but the type system must judge type of an expression without looking at its value.

一个替代的检查是 length xs = = 0 ,这不需要相等,但如果你的列表是无限的,不会停止(try length [1 ..] == 0 )。这是为什么有一个专门的函数。

An alternate check would be length xs == 0, this doesn't require equality but won't stop if your list is infinite (try length [1..] == 0). That's why there's a dedicated function.

null [] = True
null _ = False

Prelude> :t null
null :: [a] -> Bool     -- Notice lack of (Eq a).

这篇关于null而不是==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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