Why use null function instead of == []What does the `forall` keyword in Haskell/GHC do?Large-scale design in Haskell?null instead of ==Checking for a particular data constructorWhat is Weak Head Normal Form?How can a time function exist in functional programming?Why the cycle function cannot work with empty list?haskell function given type signature of booleanHaskell multiple tuple check in listHaskell null main function

Ragged justification of captions depending on odd/even page

Cubic programming and beyond?

Does entangle require vegetation?

Meaning of slash chord without anything left of the slash

Why limit to revolvers?

Why do they not say "The Baby"

Waiting time distribution parameters given expected mean

Too many spies!

What are some symbols representing peasants/oppressed persons fighting back?

Should you avoid redundant information after dialogue?

Why does the trade federation become so alarmed upon learning the ambassadors are Jedi Knights?

Published paper containing well-known results

How are "soeben" and "eben" different from one another?

Remove intersect line for one circle using venndiagram2sets

Is killing off one of my queer characters homophobic?

Replacing URI when using dynamic hosts in Nginx reverse proxy

Absconding a company after 1st day of joining

Alternatives to using writing paper for writing practice

3D-Plot with an inequality condition for parameter values

Align by center of symbol

What is the closed form of the following recursive function?

Could the crash sites of the Apollo 11 and 16 LMs be seen by the LRO?

How did Southern slaveholders in the United States relate to the Caribbean and Latin America?

Old short story where the future emperor of the galaxy is taken for a tour around Earth



Why use null function instead of == []


What does the `forall` keyword in Haskell/GHC do?Large-scale design in Haskell?null instead of ==Checking for a particular data constructorWhat is Weak Head Normal Form?How can a time function exist in functional programming?Why the cycle function cannot work with empty list?haskell function given type signature of booleanHaskell multiple tuple check in listHaskell null main function






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








8















I am reading through Learn you a haskell.It says:




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)




I tried in ghci:



xs = []
xs == []
null xs


Both of them are True.



I wonder what`s the different.
Should I use null function instead of == [] and why?










share|improve this question




























    8















    I am reading through Learn you a haskell.It says:




    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)




    I tried in ghci:



    xs = []
    xs == []
    null xs


    Both of them are True.



    I wonder what`s the different.
    Should I use null function instead of == [] and why?










    share|improve this question
























      8












      8








      8








      I am reading through Learn you a haskell.It says:




      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)




      I tried in ghci:



      xs = []
      xs == []
      null xs


      Both of them are True.



      I wonder what`s the different.
      Should I use null function instead of == [] and why?










      share|improve this question














      I am reading through Learn you a haskell.It says:




      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)




      I tried in ghci:



      xs = []
      xs == []
      null xs


      Both of them are True.



      I wonder what`s the different.
      Should I use null function instead of == [] and why?







      haskell






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 9 hours ago









      徐保钰徐保钰

      839 bronze badges




      839 bronze badges






















          4 Answers
          4






          active

          oldest

          votes


















          11














          You should use null. In most cases it doesn't matter, but it is a good habit to get into anyway, because occasionally you may want to check if a list of non-comparable things is empty. Here is a short, crisp example showing this difference:



          > null [id]
          False
          > [id] == []
          <interactive>:1:1: error:
          • No instance for (Eq (a0 -> a0)) arising from a use of ‘==’
          (maybe you haven't applied a function to enough arguments?)
          • In the expression: [id] == []
          In an equation for ‘it’: it = [id] == []





          share|improve this answer


















          • 4





            “In most cases it doesn't matter” – I'd disagree. It's very common to write polymorphic list functions, which shouldn't require an Eq constraint (even if they will indeed in most cases be instantiated with Eq types).

            – leftaroundabout
            8 hours ago



















          10














          There is a difference. In order to use x == [], the type of the elements should be a member of the Eq typeclass. Indeed, checking the equality of two elements is defined by:



          instance Eq a => Eq a where
          [] == [] = True
          (x:xs) == (y:ys) = x == y && xs == ys
          _ == _ = False


          That means that you can not use x == [] if x is for example a list of IO Ints.



          null :: [a] -> Bool on the other hand, uses pattern matching. This is implemented as:



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


          So regardless what the type of the elements of the list are, it will at least typecheck.






          share|improve this answer






























            5














            In addition to the good answers given so far, null actually has type



            null :: Foldable t => t a -> Bool


            I don't know if you've gotten to typeclasses in LYAH, but the short of it is that null can be used not just for lists, but for any data structure that implements null.



            This is to say that using null on a Map or a Set is valid, too.



            > null Map.empty
            True
            > null (Map.singleton 1)
            False
            > null Set.empty
            True
            > null (Set.singleton 1)
            False
            > null []
            True
            > null [1]
            False


            I don't think it's especially common to write functions that need to be this general, but it doesn't hurt to default to writing more general code.



            A side note



            In many cases, you'll end up wanting to use a function like null to do conditional behavior on a list (or other data structure). If you already know that your input is a specific data structure, it's more elegant to just pattern match on its empty case.



            Compare



            myMap :: (a -> b) -> [a] -> [b]
            myMap f xs
            | null xs = []
            myMap f (x:xs) = f x : myMap f xs


            to



            myMap' :: (a -> b) -> [a] -> [b]
            myMap' f [] = []
            myMap' f (x:xs) = f x : myMap' f xs


            In general, you should try to prefer pattern matching if it makes sense.






            share|improve this answer























            • exactly, I was thinking about that too when a look up for the type, plus one!

              – Damian Lattenero
              6 hours ago


















            1














            Also a simple function that filter all empty list would fail:



            withoutEmpty = filter (== [])


            and that would be:



            withoutEmpty = filter null


            Also look at @cole answer, it complements all the answers here, the typeclass Foldable has the null function there to be implemented:



            To see more info of Foldable here






            share|improve this answer



























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57029258%2fwhy-use-null-function-instead-of%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              11














              You should use null. In most cases it doesn't matter, but it is a good habit to get into anyway, because occasionally you may want to check if a list of non-comparable things is empty. Here is a short, crisp example showing this difference:



              > null [id]
              False
              > [id] == []
              <interactive>:1:1: error:
              • No instance for (Eq (a0 -> a0)) arising from a use of ‘==’
              (maybe you haven't applied a function to enough arguments?)
              • In the expression: [id] == []
              In an equation for ‘it’: it = [id] == []





              share|improve this answer


















              • 4





                “In most cases it doesn't matter” – I'd disagree. It's very common to write polymorphic list functions, which shouldn't require an Eq constraint (even if they will indeed in most cases be instantiated with Eq types).

                – leftaroundabout
                8 hours ago
















              11














              You should use null. In most cases it doesn't matter, but it is a good habit to get into anyway, because occasionally you may want to check if a list of non-comparable things is empty. Here is a short, crisp example showing this difference:



              > null [id]
              False
              > [id] == []
              <interactive>:1:1: error:
              • No instance for (Eq (a0 -> a0)) arising from a use of ‘==’
              (maybe you haven't applied a function to enough arguments?)
              • In the expression: [id] == []
              In an equation for ‘it’: it = [id] == []





              share|improve this answer


















              • 4





                “In most cases it doesn't matter” – I'd disagree. It's very common to write polymorphic list functions, which shouldn't require an Eq constraint (even if they will indeed in most cases be instantiated with Eq types).

                – leftaroundabout
                8 hours ago














              11












              11








              11







              You should use null. In most cases it doesn't matter, but it is a good habit to get into anyway, because occasionally you may want to check if a list of non-comparable things is empty. Here is a short, crisp example showing this difference:



              > null [id]
              False
              > [id] == []
              <interactive>:1:1: error:
              • No instance for (Eq (a0 -> a0)) arising from a use of ‘==’
              (maybe you haven't applied a function to enough arguments?)
              • In the expression: [id] == []
              In an equation for ‘it’: it = [id] == []





              share|improve this answer













              You should use null. In most cases it doesn't matter, but it is a good habit to get into anyway, because occasionally you may want to check if a list of non-comparable things is empty. Here is a short, crisp example showing this difference:



              > null [id]
              False
              > [id] == []
              <interactive>:1:1: error:
              • No instance for (Eq (a0 -> a0)) arising from a use of ‘==’
              (maybe you haven't applied a function to enough arguments?)
              • In the expression: [id] == []
              In an equation for ‘it’: it = [id] == []






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 9 hours ago









              Daniel WagnerDaniel Wagner

              108k7 gold badges170 silver badges301 bronze badges




              108k7 gold badges170 silver badges301 bronze badges







              • 4





                “In most cases it doesn't matter” – I'd disagree. It's very common to write polymorphic list functions, which shouldn't require an Eq constraint (even if they will indeed in most cases be instantiated with Eq types).

                – leftaroundabout
                8 hours ago













              • 4





                “In most cases it doesn't matter” – I'd disagree. It's very common to write polymorphic list functions, which shouldn't require an Eq constraint (even if they will indeed in most cases be instantiated with Eq types).

                – leftaroundabout
                8 hours ago








              4




              4





              “In most cases it doesn't matter” – I'd disagree. It's very common to write polymorphic list functions, which shouldn't require an Eq constraint (even if they will indeed in most cases be instantiated with Eq types).

              – leftaroundabout
              8 hours ago






              “In most cases it doesn't matter” – I'd disagree. It's very common to write polymorphic list functions, which shouldn't require an Eq constraint (even if they will indeed in most cases be instantiated with Eq types).

              – leftaroundabout
              8 hours ago














              10














              There is a difference. In order to use x == [], the type of the elements should be a member of the Eq typeclass. Indeed, checking the equality of two elements is defined by:



              instance Eq a => Eq a where
              [] == [] = True
              (x:xs) == (y:ys) = x == y && xs == ys
              _ == _ = False


              That means that you can not use x == [] if x is for example a list of IO Ints.



              null :: [a] -> Bool on the other hand, uses pattern matching. This is implemented as:



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


              So regardless what the type of the elements of the list are, it will at least typecheck.






              share|improve this answer



























                10














                There is a difference. In order to use x == [], the type of the elements should be a member of the Eq typeclass. Indeed, checking the equality of two elements is defined by:



                instance Eq a => Eq a where
                [] == [] = True
                (x:xs) == (y:ys) = x == y && xs == ys
                _ == _ = False


                That means that you can not use x == [] if x is for example a list of IO Ints.



                null :: [a] -> Bool on the other hand, uses pattern matching. This is implemented as:



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


                So regardless what the type of the elements of the list are, it will at least typecheck.






                share|improve this answer

























                  10












                  10








                  10







                  There is a difference. In order to use x == [], the type of the elements should be a member of the Eq typeclass. Indeed, checking the equality of two elements is defined by:



                  instance Eq a => Eq a where
                  [] == [] = True
                  (x:xs) == (y:ys) = x == y && xs == ys
                  _ == _ = False


                  That means that you can not use x == [] if x is for example a list of IO Ints.



                  null :: [a] -> Bool on the other hand, uses pattern matching. This is implemented as:



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


                  So regardless what the type of the elements of the list are, it will at least typecheck.






                  share|improve this answer













                  There is a difference. In order to use x == [], the type of the elements should be a member of the Eq typeclass. Indeed, checking the equality of two elements is defined by:



                  instance Eq a => Eq a where
                  [] == [] = True
                  (x:xs) == (y:ys) = x == y && xs == ys
                  _ == _ = False


                  That means that you can not use x == [] if x is for example a list of IO Ints.



                  null :: [a] -> Bool on the other hand, uses pattern matching. This is implemented as:



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


                  So regardless what the type of the elements of the list are, it will at least typecheck.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 9 hours ago









                  Willem Van OnsemWillem Van Onsem

                  170k18 gold badges171 silver badges259 bronze badges




                  170k18 gold badges171 silver badges259 bronze badges





















                      5














                      In addition to the good answers given so far, null actually has type



                      null :: Foldable t => t a -> Bool


                      I don't know if you've gotten to typeclasses in LYAH, but the short of it is that null can be used not just for lists, but for any data structure that implements null.



                      This is to say that using null on a Map or a Set is valid, too.



                      > null Map.empty
                      True
                      > null (Map.singleton 1)
                      False
                      > null Set.empty
                      True
                      > null (Set.singleton 1)
                      False
                      > null []
                      True
                      > null [1]
                      False


                      I don't think it's especially common to write functions that need to be this general, but it doesn't hurt to default to writing more general code.



                      A side note



                      In many cases, you'll end up wanting to use a function like null to do conditional behavior on a list (or other data structure). If you already know that your input is a specific data structure, it's more elegant to just pattern match on its empty case.



                      Compare



                      myMap :: (a -> b) -> [a] -> [b]
                      myMap f xs
                      | null xs = []
                      myMap f (x:xs) = f x : myMap f xs


                      to



                      myMap' :: (a -> b) -> [a] -> [b]
                      myMap' f [] = []
                      myMap' f (x:xs) = f x : myMap' f xs


                      In general, you should try to prefer pattern matching if it makes sense.






                      share|improve this answer























                      • exactly, I was thinking about that too when a look up for the type, plus one!

                        – Damian Lattenero
                        6 hours ago















                      5














                      In addition to the good answers given so far, null actually has type



                      null :: Foldable t => t a -> Bool


                      I don't know if you've gotten to typeclasses in LYAH, but the short of it is that null can be used not just for lists, but for any data structure that implements null.



                      This is to say that using null on a Map or a Set is valid, too.



                      > null Map.empty
                      True
                      > null (Map.singleton 1)
                      False
                      > null Set.empty
                      True
                      > null (Set.singleton 1)
                      False
                      > null []
                      True
                      > null [1]
                      False


                      I don't think it's especially common to write functions that need to be this general, but it doesn't hurt to default to writing more general code.



                      A side note



                      In many cases, you'll end up wanting to use a function like null to do conditional behavior on a list (or other data structure). If you already know that your input is a specific data structure, it's more elegant to just pattern match on its empty case.



                      Compare



                      myMap :: (a -> b) -> [a] -> [b]
                      myMap f xs
                      | null xs = []
                      myMap f (x:xs) = f x : myMap f xs


                      to



                      myMap' :: (a -> b) -> [a] -> [b]
                      myMap' f [] = []
                      myMap' f (x:xs) = f x : myMap' f xs


                      In general, you should try to prefer pattern matching if it makes sense.






                      share|improve this answer























                      • exactly, I was thinking about that too when a look up for the type, plus one!

                        – Damian Lattenero
                        6 hours ago













                      5












                      5








                      5







                      In addition to the good answers given so far, null actually has type



                      null :: Foldable t => t a -> Bool


                      I don't know if you've gotten to typeclasses in LYAH, but the short of it is that null can be used not just for lists, but for any data structure that implements null.



                      This is to say that using null on a Map or a Set is valid, too.



                      > null Map.empty
                      True
                      > null (Map.singleton 1)
                      False
                      > null Set.empty
                      True
                      > null (Set.singleton 1)
                      False
                      > null []
                      True
                      > null [1]
                      False


                      I don't think it's especially common to write functions that need to be this general, but it doesn't hurt to default to writing more general code.



                      A side note



                      In many cases, you'll end up wanting to use a function like null to do conditional behavior on a list (or other data structure). If you already know that your input is a specific data structure, it's more elegant to just pattern match on its empty case.



                      Compare



                      myMap :: (a -> b) -> [a] -> [b]
                      myMap f xs
                      | null xs = []
                      myMap f (x:xs) = f x : myMap f xs


                      to



                      myMap' :: (a -> b) -> [a] -> [b]
                      myMap' f [] = []
                      myMap' f (x:xs) = f x : myMap' f xs


                      In general, you should try to prefer pattern matching if it makes sense.






                      share|improve this answer













                      In addition to the good answers given so far, null actually has type



                      null :: Foldable t => t a -> Bool


                      I don't know if you've gotten to typeclasses in LYAH, but the short of it is that null can be used not just for lists, but for any data structure that implements null.



                      This is to say that using null on a Map or a Set is valid, too.



                      > null Map.empty
                      True
                      > null (Map.singleton 1)
                      False
                      > null Set.empty
                      True
                      > null (Set.singleton 1)
                      False
                      > null []
                      True
                      > null [1]
                      False


                      I don't think it's especially common to write functions that need to be this general, but it doesn't hurt to default to writing more general code.



                      A side note



                      In many cases, you'll end up wanting to use a function like null to do conditional behavior on a list (or other data structure). If you already know that your input is a specific data structure, it's more elegant to just pattern match on its empty case.



                      Compare



                      myMap :: (a -> b) -> [a] -> [b]
                      myMap f xs
                      | null xs = []
                      myMap f (x:xs) = f x : myMap f xs


                      to



                      myMap' :: (a -> b) -> [a] -> [b]
                      myMap' f [] = []
                      myMap' f (x:xs) = f x : myMap' f xs


                      In general, you should try to prefer pattern matching if it makes sense.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 6 hours ago









                      colecole

                      2152 silver badges10 bronze badges




                      2152 silver badges10 bronze badges












                      • exactly, I was thinking about that too when a look up for the type, plus one!

                        – Damian Lattenero
                        6 hours ago

















                      • exactly, I was thinking about that too when a look up for the type, plus one!

                        – Damian Lattenero
                        6 hours ago
















                      exactly, I was thinking about that too when a look up for the type, plus one!

                      – Damian Lattenero
                      6 hours ago





                      exactly, I was thinking about that too when a look up for the type, plus one!

                      – Damian Lattenero
                      6 hours ago











                      1














                      Also a simple function that filter all empty list would fail:



                      withoutEmpty = filter (== [])


                      and that would be:



                      withoutEmpty = filter null


                      Also look at @cole answer, it complements all the answers here, the typeclass Foldable has the null function there to be implemented:



                      To see more info of Foldable here






                      share|improve this answer





























                        1














                        Also a simple function that filter all empty list would fail:



                        withoutEmpty = filter (== [])


                        and that would be:



                        withoutEmpty = filter null


                        Also look at @cole answer, it complements all the answers here, the typeclass Foldable has the null function there to be implemented:



                        To see more info of Foldable here






                        share|improve this answer



























                          1












                          1








                          1







                          Also a simple function that filter all empty list would fail:



                          withoutEmpty = filter (== [])


                          and that would be:



                          withoutEmpty = filter null


                          Also look at @cole answer, it complements all the answers here, the typeclass Foldable has the null function there to be implemented:



                          To see more info of Foldable here






                          share|improve this answer















                          Also a simple function that filter all empty list would fail:



                          withoutEmpty = filter (== [])


                          and that would be:



                          withoutEmpty = filter null


                          Also look at @cole answer, it complements all the answers here, the typeclass Foldable has the null function there to be implemented:



                          To see more info of Foldable here







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited 6 hours ago

























                          answered 6 hours ago









                          Damian LatteneroDamian Lattenero

                          9,7662 gold badges20 silver badges45 bronze badges




                          9,7662 gold badges20 silver badges45 bronze badges



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57029258%2fwhy-use-null-function-instead-of%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              ParseJSON using SSJSUsing AMPscript with SSJS ActivitiesHow to resubscribe a user in Marketing cloud using SSJS?Pulling Subscriber Status from Lists using SSJSRetrieving Emails using SSJSProblem in updating DE using SSJSUsing SSJS to send single email in Marketing CloudError adding EmailSendDefinition using SSJS

                              Кампала Садржај Географија Географија Историја Становништво Привреда Партнерски градови Референце Спољашње везе Мени за навигацију0°11′ СГШ; 32°20′ ИГД / 0.18° СГШ; 32.34° ИГД / 0.18; 32.340°11′ СГШ; 32°20′ ИГД / 0.18° СГШ; 32.34° ИГД / 0.18; 32.34МедијиПодациЗванични веб-сајту

                              19. јануар Садржај Догађаји Рођења Смрти Празници и дани сећања Види још Референце Мени за навигацијуу