Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 空而不是==_Haskell_Coding Style_Operators_Typeclass - Fatal编程技术网

Haskell 空而不是==

Haskell 空而不是==,haskell,coding-style,operators,typeclass,Haskell,Coding Style,Operators,Typeclass,出于兴趣,我刚开始学习哈斯克尔。我跟着 在那里我发现了这个: null检查列表是否为空。如果是 是,则返回True,否则返回 返回False。使用此功能 而不是xs=[](如果您有 列表名为xs) 为什么呢?当两者产生相同的结果时,为什么我们应该使用null而不是= 谢谢。在我看来,null myList比myList=[]读起来更自然 但是null存在的理由是它可以用作函数。例如,下面是一个函数,它获取列表列表,并仅返回非空列表: nonemptyLists :: [[a]] -> [[

出于兴趣,我刚开始学习哈斯克尔。我跟着

在那里我发现了这个:

null
检查列表是否为空。如果是 是,则返回
True
,否则返回 返回
False
。使用此功能 而不是
xs=[]
(如果您有 列表名为
xs

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


谢谢。

在我看来,
null myList
myList=[]
读起来更自然

但是
null
存在的理由是它可以用作函数。例如,下面是一个函数,它获取列表列表,并仅返回非空列表:

nonemptyLists :: [[a]] -> [[a]]
nonemptyLists = filter (not . null)
如果没有
null
,这将更加尴尬:

nonEmptyLists = filter ([] /=)

将列表与
==
进行比较需要元素具有可比性(表示为
等式a

例如,
[sin]=[]
将不起作用,因为您无法比较函数。这可能看起来很愚蠢,但类型系统必须判断表达式的类型而不查看其值

另一个检查是
length xs==0
,这不要求相等,但如果列表无限大,则不会停止(请尝试
length[1..]==0
)。这就是为什么有专门的功能

null [] = True
null _ = False

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

使用
null
的另一个好处是许多其他容器(例如Data.Sequence、Data.ByteString等)也具有
null
功能。这使得只需更改导入语句即可轻松切换到另一个实现。

如何更自然地反转操作数和准备:
过滤器(/=[])
。请注意,我总是更喜欢模式匹配而不是相等运算符(除非在上面将其用作函数的情况下),请参见sdcvvc的回答:真正的原因是
null
适用于任何列表,而
(=[])
仅适用于
Eq
@KennyTM的列表:当然,修复了。谢谢@皮特·德尔波特:我没有想到@sdcvvc:+1:)难道
(/=[])
不是更自然吗?(好吧,除非你喜欢尤达的条件。)大概吧。重点是要表现出尴尬,嗯?;)很好的问题。顺便说一句,我还没有想到这个问题。(也在学习哈斯克尔)
null [] = True
null _ = False

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