如何在Haskell中生成无穷大?类比NaN生成,是否仅能通过1/0实现?
Great question! You’re right that the ClassyPrelude Math module only includes tools to detect infinity, rather than generate it directly—unlike C’s INFINITY macro. But you’ve got more options than just 1/0! Let’s break them down:
Arithmetic operations (the straightforward go-to)
As you noted, dividing a positive floating-point number by zero gives positive infinity. Just make sure you’re using a floating-point type (likeDoubleorFloat) instead of integers—integer division by zero will throw an error instead of producing infinity. Example code:positiveInf :: Double positiveInf = 1.0 / 0.0 -- Results in Infinity negativeInf :: Double negativeInf = -1.0 / 0.0 -- Results in -InfinityUse GHC’s pre-defined infinity values
TheGHC.Floatmodule (part of Haskell’s base library, no extra dependencies needed) exports directinfinityandnegInfinityvalues forFloat. You can easily convert these toDoubletoo:import GHC.Float (infinity, negInfinity) floatInf :: Float floatInf = infinity doubleInf :: Double doubleInf = realToFrac infinity -- Convert Float infinity to DoubleFor
Doublespecifically, you can also useread "Infinity" :: Double—theReadinstance for floating-point types supports parsing "Infinity" and "-Infinity" directly.Lower-level manual construction (for deep dives)
If you want to build infinity from scratch without relying on division or pre-made values, useencodeFloatfrom theFloatingtypeclass. ForDouble, infinity is created by setting the exponent to its maximum possible value and the mantissa to 0:import Data.Word (Word64) import GHC.Float (encodeDouble) manualDoubleInf :: Double manualDoubleInf = encodeDouble 0 (maxBound :: Word64)This is more of an advanced method though—for most everyday use cases, the first two options are simpler and more readable.
A quick note: All these methods only work for floating-point types (Float, Double, etc.). Haskell’s integer types don’t support infinity, since they represent exact whole numbers.
内容的提问来源于stack exchange,提问作者user4385532

