You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Haskell中生成无穷大?类比NaN生成,是否仅能通过1/0实现?

Generating Infinity in Haskell

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 (like Double or Float) 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 -Infinity
    
  • Use GHC’s pre-defined infinity values
    The GHC.Float module (part of Haskell’s base library, no extra dependencies needed) exports direct infinity and negInfinity values for Float. You can easily convert these to Double too:

    import GHC.Float (infinity, negInfinity)
    
    floatInf :: Float
    floatInf = infinity
    
    doubleInf :: Double
    doubleInf = realToFrac infinity  -- Convert Float infinity to Double
    

    For Double specifically, you can also use read "Infinity" :: Double—the Read instance 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, use encodeFloat from the Floating typeclass. For Double, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:28:50