In Haskell, is there infinity :: Num a => a?

后端 未结 8 1771
孤城傲影
孤城傲影 2020-12-16 10:03

I\'m trying to implement a data structure where if I had the use of infinity for numerical comparison purposes, it would simply things greatly. Note this isn\'t maxBound/min

相关标签:
8条回答
  • 2020-12-16 11:00

    Try something like this. However, to get Num operations (like + or -) you will need to define Num instance for Infinitable a type. Just like I've done it for Ord class.

    data Infinitable a = Regular a | NegativeInfinity | PositiveInfinity deriving (Eq, Show)
    
    instance Ord a => Ord (Infinitable a) where
        compare NegativeInfinity NegativeInfinity = EQ
        compare PositiveInfinity PositiveInfinity = EQ
        compare NegativeInfinity _ = LT
        compare PositiveInfinity _ = GT
        compare _ PositiveInfinity = LT
        compare _ NegativeInfinity = GT
        compare (Regular x) (Regular y) = compare x y    
    
    main =
        let five = Regular 5
            pinf = PositiveInfinity::Infinitable Integer
            ninf = NegativeInfinity::Infinitable Integer
            results = [(pinf > five), (ninf < pinf), (five > ninf)]
        in
            do putStrLn (show results)
    
    0 讨论(0)
  • 2020-12-16 11:00

    Take a look at my RangedSets library, which does exactly this in a very general way. I defined a "Boundary" type so that a value of type "Boundary a" is always either above or below any given "a". Boundaries can be "AboveAll", "BelowAll", "Above x" and "Below x".

    0 讨论(0)
提交回复
热议问题