Converting from newtype to Int and from Int to newtype










2















How do I convert newtype to Int and vice versa?



I tried:



newtype NT1 = NT1 Integer

fromNT1toInt :: NT1 -> Int
fromNT1toInt x = let y = x :: Int
in y


but I get could't match expected type error



I tried making NT1 instance of Enum class
but I don't understand well how does toEnum work



newtype NT1 = NT1 Integer

instance Enum NT1 where
toEnum x = let x = x :: Integer
in if x >= 0
then x :: NT1
else x :: NT1


when I call toEnum 5 :: NT1 this should return 5 NT1 but I get StackOverflow error.
Where am I making mistake?



Edited: newtype name










share|improve this question




























    2















    How do I convert newtype to Int and vice versa?



    I tried:



    newtype NT1 = NT1 Integer

    fromNT1toInt :: NT1 -> Int
    fromNT1toInt x = let y = x :: Int
    in y


    but I get could't match expected type error



    I tried making NT1 instance of Enum class
    but I don't understand well how does toEnum work



    newtype NT1 = NT1 Integer

    instance Enum NT1 where
    toEnum x = let x = x :: Integer
    in if x >= 0
    then x :: NT1
    else x :: NT1


    when I call toEnum 5 :: NT1 this should return 5 NT1 but I get StackOverflow error.
    Where am I making mistake?



    Edited: newtype name










    share|improve this question


























      2












      2








      2








      How do I convert newtype to Int and vice versa?



      I tried:



      newtype NT1 = NT1 Integer

      fromNT1toInt :: NT1 -> Int
      fromNT1toInt x = let y = x :: Int
      in y


      but I get could't match expected type error



      I tried making NT1 instance of Enum class
      but I don't understand well how does toEnum work



      newtype NT1 = NT1 Integer

      instance Enum NT1 where
      toEnum x = let x = x :: Integer
      in if x >= 0
      then x :: NT1
      else x :: NT1


      when I call toEnum 5 :: NT1 this should return 5 NT1 but I get StackOverflow error.
      Where am I making mistake?



      Edited: newtype name










      share|improve this question
















      How do I convert newtype to Int and vice versa?



      I tried:



      newtype NT1 = NT1 Integer

      fromNT1toInt :: NT1 -> Int
      fromNT1toInt x = let y = x :: Int
      in y


      but I get could't match expected type error



      I tried making NT1 instance of Enum class
      but I don't understand well how does toEnum work



      newtype NT1 = NT1 Integer

      instance Enum NT1 where
      toEnum x = let x = x :: Integer
      in if x >= 0
      then x :: NT1
      else x :: NT1


      when I call toEnum 5 :: NT1 this should return 5 NT1 but I get StackOverflow error.
      Where am I making mistake?



      Edited: newtype name







      haskell






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 13 '18 at 13:26









      Micha Wiedenmann

      10.3k1364103




      10.3k1364103










      asked Nov 13 '18 at 4:03









      cheshirecheshire

      1898




      1898






















          2 Answers
          2






          active

          oldest

          votes


















          4














          Use fromIntegral to convert between integral types, such as Int and Integer. Use NT1 to convert from Integer to NT1, and pattern-matching from NT1 to Integer. Finally, you can compose functions to connect things.



          toNT1 :: Int -> NT1
          toNT1 = NT1 . fromIntegral

          fromNT1 :: NT1 -> Int
          fromNT1 (NT1 x) = fromIntegral x





          share|improve this answer
































            6














            e :: t doesn’t mean “convert expression e to type t”, it’s just an annotation that says “e has type t (already)”. So this:



            let y = x :: Int in y


            Means: assert that x has type Int, set y equal to x, and return y. That’s why you got a type mismatch: x does not have type Int as you are claiming to the compiler. And this:



            let x = x :: Integer
            in if x >= 0 then x :: NT1 else x :: NT1


            Means: declare a new variable x, set it equal to itself (an infinite loop), asserting that it has type Integer, then test whether that infinite loop returns a nonnegative value; either way, return x, asserting that it has type NT1 (this contradicts the Integer from before).



            To convert between Integer and Int, you can use fromIntegral :: (Integral a, Num b) => a -> b, which converts any integral type (such as Int or Integer) into any numeric type (such as Int, Integer, Float, Double, or Ratio).



            For converting from newtypes, you can use pattern-matching:



            fromNT1ToInt :: NT1 -> Int
            fromNT1ToInt (NT1 x) = fromIntegral x


            Or add a record accessor function to the newtype and use that:



            newtype NT1 = NT1 nt1Val :: Integer 
            -- Note: nt1Val :: NT1 -> Integer

            fromNT1ToInt :: NT1 -> Int
            fromNT1ToInt nt = fromIntegral (nt1Val nt)
            -- Or, with function composition (.):
            fromNT1ToInt = fromIntegral . nt1Val


            Or, finally, use coerce from Data.Coerce:



            import Data.Coerce (coerce)

            fromNT1ToInt :: NT1 -> Int
            fromNT1ToInt nt = fromIntegral (coerce nt :: Integer)


            And of course, to construct a newtype you just use its constructor—in this case, NT1 :: Integer -> NT1, e.g. NT1 5.






            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%2f53273610%2fconverting-from-newtype-to-int-and-from-int-to-newtype%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              4














              Use fromIntegral to convert between integral types, such as Int and Integer. Use NT1 to convert from Integer to NT1, and pattern-matching from NT1 to Integer. Finally, you can compose functions to connect things.



              toNT1 :: Int -> NT1
              toNT1 = NT1 . fromIntegral

              fromNT1 :: NT1 -> Int
              fromNT1 (NT1 x) = fromIntegral x





              share|improve this answer





























                4














                Use fromIntegral to convert between integral types, such as Int and Integer. Use NT1 to convert from Integer to NT1, and pattern-matching from NT1 to Integer. Finally, you can compose functions to connect things.



                toNT1 :: Int -> NT1
                toNT1 = NT1 . fromIntegral

                fromNT1 :: NT1 -> Int
                fromNT1 (NT1 x) = fromIntegral x





                share|improve this answer



























                  4












                  4








                  4







                  Use fromIntegral to convert between integral types, such as Int and Integer. Use NT1 to convert from Integer to NT1, and pattern-matching from NT1 to Integer. Finally, you can compose functions to connect things.



                  toNT1 :: Int -> NT1
                  toNT1 = NT1 . fromIntegral

                  fromNT1 :: NT1 -> Int
                  fromNT1 (NT1 x) = fromIntegral x





                  share|improve this answer















                  Use fromIntegral to convert between integral types, such as Int and Integer. Use NT1 to convert from Integer to NT1, and pattern-matching from NT1 to Integer. Finally, you can compose functions to connect things.



                  toNT1 :: Int -> NT1
                  toNT1 = NT1 . fromIntegral

                  fromNT1 :: NT1 -> Int
                  fromNT1 (NT1 x) = fromIntegral x






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 13 '18 at 4:23

























                  answered Nov 13 '18 at 4:07









                  Li-yao XiaLi-yao Xia

                  12k1327




                  12k1327























                      6














                      e :: t doesn’t mean “convert expression e to type t”, it’s just an annotation that says “e has type t (already)”. So this:



                      let y = x :: Int in y


                      Means: assert that x has type Int, set y equal to x, and return y. That’s why you got a type mismatch: x does not have type Int as you are claiming to the compiler. And this:



                      let x = x :: Integer
                      in if x >= 0 then x :: NT1 else x :: NT1


                      Means: declare a new variable x, set it equal to itself (an infinite loop), asserting that it has type Integer, then test whether that infinite loop returns a nonnegative value; either way, return x, asserting that it has type NT1 (this contradicts the Integer from before).



                      To convert between Integer and Int, you can use fromIntegral :: (Integral a, Num b) => a -> b, which converts any integral type (such as Int or Integer) into any numeric type (such as Int, Integer, Float, Double, or Ratio).



                      For converting from newtypes, you can use pattern-matching:



                      fromNT1ToInt :: NT1 -> Int
                      fromNT1ToInt (NT1 x) = fromIntegral x


                      Or add a record accessor function to the newtype and use that:



                      newtype NT1 = NT1 nt1Val :: Integer 
                      -- Note: nt1Val :: NT1 -> Integer

                      fromNT1ToInt :: NT1 -> Int
                      fromNT1ToInt nt = fromIntegral (nt1Val nt)
                      -- Or, with function composition (.):
                      fromNT1ToInt = fromIntegral . nt1Val


                      Or, finally, use coerce from Data.Coerce:



                      import Data.Coerce (coerce)

                      fromNT1ToInt :: NT1 -> Int
                      fromNT1ToInt nt = fromIntegral (coerce nt :: Integer)


                      And of course, to construct a newtype you just use its constructor—in this case, NT1 :: Integer -> NT1, e.g. NT1 5.






                      share|improve this answer



























                        6














                        e :: t doesn’t mean “convert expression e to type t”, it’s just an annotation that says “e has type t (already)”. So this:



                        let y = x :: Int in y


                        Means: assert that x has type Int, set y equal to x, and return y. That’s why you got a type mismatch: x does not have type Int as you are claiming to the compiler. And this:



                        let x = x :: Integer
                        in if x >= 0 then x :: NT1 else x :: NT1


                        Means: declare a new variable x, set it equal to itself (an infinite loop), asserting that it has type Integer, then test whether that infinite loop returns a nonnegative value; either way, return x, asserting that it has type NT1 (this contradicts the Integer from before).



                        To convert between Integer and Int, you can use fromIntegral :: (Integral a, Num b) => a -> b, which converts any integral type (such as Int or Integer) into any numeric type (such as Int, Integer, Float, Double, or Ratio).



                        For converting from newtypes, you can use pattern-matching:



                        fromNT1ToInt :: NT1 -> Int
                        fromNT1ToInt (NT1 x) = fromIntegral x


                        Or add a record accessor function to the newtype and use that:



                        newtype NT1 = NT1 nt1Val :: Integer 
                        -- Note: nt1Val :: NT1 -> Integer

                        fromNT1ToInt :: NT1 -> Int
                        fromNT1ToInt nt = fromIntegral (nt1Val nt)
                        -- Or, with function composition (.):
                        fromNT1ToInt = fromIntegral . nt1Val


                        Or, finally, use coerce from Data.Coerce:



                        import Data.Coerce (coerce)

                        fromNT1ToInt :: NT1 -> Int
                        fromNT1ToInt nt = fromIntegral (coerce nt :: Integer)


                        And of course, to construct a newtype you just use its constructor—in this case, NT1 :: Integer -> NT1, e.g. NT1 5.






                        share|improve this answer

























                          6












                          6








                          6







                          e :: t doesn’t mean “convert expression e to type t”, it’s just an annotation that says “e has type t (already)”. So this:



                          let y = x :: Int in y


                          Means: assert that x has type Int, set y equal to x, and return y. That’s why you got a type mismatch: x does not have type Int as you are claiming to the compiler. And this:



                          let x = x :: Integer
                          in if x >= 0 then x :: NT1 else x :: NT1


                          Means: declare a new variable x, set it equal to itself (an infinite loop), asserting that it has type Integer, then test whether that infinite loop returns a nonnegative value; either way, return x, asserting that it has type NT1 (this contradicts the Integer from before).



                          To convert between Integer and Int, you can use fromIntegral :: (Integral a, Num b) => a -> b, which converts any integral type (such as Int or Integer) into any numeric type (such as Int, Integer, Float, Double, or Ratio).



                          For converting from newtypes, you can use pattern-matching:



                          fromNT1ToInt :: NT1 -> Int
                          fromNT1ToInt (NT1 x) = fromIntegral x


                          Or add a record accessor function to the newtype and use that:



                          newtype NT1 = NT1 nt1Val :: Integer 
                          -- Note: nt1Val :: NT1 -> Integer

                          fromNT1ToInt :: NT1 -> Int
                          fromNT1ToInt nt = fromIntegral (nt1Val nt)
                          -- Or, with function composition (.):
                          fromNT1ToInt = fromIntegral . nt1Val


                          Or, finally, use coerce from Data.Coerce:



                          import Data.Coerce (coerce)

                          fromNT1ToInt :: NT1 -> Int
                          fromNT1ToInt nt = fromIntegral (coerce nt :: Integer)


                          And of course, to construct a newtype you just use its constructor—in this case, NT1 :: Integer -> NT1, e.g. NT1 5.






                          share|improve this answer













                          e :: t doesn’t mean “convert expression e to type t”, it’s just an annotation that says “e has type t (already)”. So this:



                          let y = x :: Int in y


                          Means: assert that x has type Int, set y equal to x, and return y. That’s why you got a type mismatch: x does not have type Int as you are claiming to the compiler. And this:



                          let x = x :: Integer
                          in if x >= 0 then x :: NT1 else x :: NT1


                          Means: declare a new variable x, set it equal to itself (an infinite loop), asserting that it has type Integer, then test whether that infinite loop returns a nonnegative value; either way, return x, asserting that it has type NT1 (this contradicts the Integer from before).



                          To convert between Integer and Int, you can use fromIntegral :: (Integral a, Num b) => a -> b, which converts any integral type (such as Int or Integer) into any numeric type (such as Int, Integer, Float, Double, or Ratio).



                          For converting from newtypes, you can use pattern-matching:



                          fromNT1ToInt :: NT1 -> Int
                          fromNT1ToInt (NT1 x) = fromIntegral x


                          Or add a record accessor function to the newtype and use that:



                          newtype NT1 = NT1 nt1Val :: Integer 
                          -- Note: nt1Val :: NT1 -> Integer

                          fromNT1ToInt :: NT1 -> Int
                          fromNT1ToInt nt = fromIntegral (nt1Val nt)
                          -- Or, with function composition (.):
                          fromNT1ToInt = fromIntegral . nt1Val


                          Or, finally, use coerce from Data.Coerce:



                          import Data.Coerce (coerce)

                          fromNT1ToInt :: NT1 -> Int
                          fromNT1ToInt nt = fromIntegral (coerce nt :: Integer)


                          And of course, to construct a newtype you just use its constructor—in this case, NT1 :: Integer -> NT1, e.g. NT1 5.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 13 '18 at 5:32









                          Jon PurdyJon Purdy

                          37.9k668125




                          37.9k668125



























                              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%2f53273610%2fconverting-from-newtype-to-int-and-from-int-to-newtype%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







                              這個網誌中的熱門文章

                              How to read a connectionString WITH PROVIDER in .NET Core?

                              In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

                              Museum of Modern and Contemporary Art of Trento and Rovereto