null instead of ==

后端 未结 3 1833
自闭症患者
自闭症患者 2021-02-05 01:31

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

There I found this:

null checks if a list is emp

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-05 01:52

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

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

    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.

    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).
    

提交回复
热议问题