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

Confused about 誘われて (Sasowarete)

How would someone destroy a black hole that’s at the centre of a planet?

Filtering fine silt/mud from water (not necessarily bacteria etc.)

How did John Lennon tune his guitar

What exactly is the Tension force?

Can a continent naturally split into two distant parts within a week?

Can I capture stereo IQ signals from WebSDR?

Does entangle require vegetation?

Why is "dark" an adverb in this sentence?

Project Euler, problem # 9, Pythagorean triplet

Is it okay to retroactively change things when running a published adventure?

Crab Nebula short story from 1960s or '70s

Are lithium batteries allowed in the International Space Station?

Deep Learning based time series forecasting

Why are Japanese translated subtitles non-conversational?

Construct a pentagon avoiding compass use

Ezek. 24:1-2, "Again in the ninth year, in the tenth month, in the tenth day of the month, ...." Which month was the tenth month?

Hot object in a vacuum

Basic example of a formal affine scheme, functorial point of view

How would you write do the dialogues of two characters talking in a chat room?

Why do candidates not quit if they no longer have a realistic chance to win in the 2020 US presidents election

Why doesn't Anakin's lightsaber explode when it's chopped in half on Geonosis?

How can we better understand multiplicative inverse modulo something?

Why limit to revolvers?



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 8 hours ago









      徐保钰徐保钰

      839 bronze badges




      839 bronze badges






















          4 Answers
          4






          active

          oldest

          votes


















          10














          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
            7 hours ago



















          9














          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
              5 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









              10














              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
                7 hours ago
















              10














              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
                7 hours ago














              10












              10








              10







              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 8 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
                7 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
                7 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
              7 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
              7 hours ago














              9














              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



























                9














                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

























                  9












                  9








                  9







                  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 8 hours ago









                  Willem Van OnsemWillem Van Onsem

                  170k18 gold badges171 silver badges258 bronze badges




                  170k18 gold badges171 silver badges258 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
                        5 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
                        5 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 5 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
                        5 hours ago

















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

                        – Damian Lattenero
                        5 hours ago
















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

                      – Damian Lattenero
                      5 hours ago





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

                      – Damian Lattenero
                      5 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 5 hours ago

























                          answered 5 hours ago









                          Damian LatteneroDamian Lattenero

                          9,7482 gold badges20 silver badges45 bronze badges




                          9,7482 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

                              Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                              Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                              Ласкавець круглолистий Зміст Опис | Поширення | Галерея | Примітки | Посилання | Навігаційне меню58171138361-22960890446Bupleurum rotundifoliumEuro+Med PlantbasePlants of the World Online — Kew ScienceGermplasm Resources Information Network (GRIN)Ласкавецькн. VI : Літери Ком — Левиправивши або дописавши її