Implementation of null function

后端 未结 3 884
盖世英雄少女心
盖世英雄少女心 2021-01-17 07:35

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

3条回答
  •  无人及你
    2021-01-17 08:13

    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.

提交回复
热议问题