Why can Haskell handle very large numbers easily?

后端 未结 8 1890
遇见更好的自我
遇见更好的自我 2021-01-01 11:09
Hugs> 94535^445
13763208823213770506960538876615156211048901640052821530697264247739998018468419032448277029434879827074549660094560167350418780006041435009085328         


        
8条回答
  •  死守一世寂寞
    2021-01-01 11:30

    Numeric literals in Haskell are overloaded so that they can represent multiple concrete types (like Int, Integer, Float or even MyOwnNumber).

    You can manually chose a specific type by providing type information, like so:

    x = 4 :: Int
    y = 4 :: Integer
    z = 4 :: Float
    

    These three values have different types and operations performed on these will behave differently.

    The exact size of an Int is implementation dependent but can be something like 28 bits, this type behaves like a Java primitive int, e.g. it will overflow.

    An Integer is a type that can contain arbitrary-precision integers, like the Java BigInteger.

    And a Float is like a Java float, using floating point arithmetic.

    Just like numeric literals, many operators are also overloaded (using type classes), and can therefor be used with the different types. So the + operator can work with both Ints and Floats.

    In your case, since you didn't provide any type information, the interpreter will default to the Integer type. This means that for the ^ operator, it will also choose the Integer instance. Allowing for arbitrary-precision integer calculations.

提交回复
热议问题