Search code examples
typespattern-matchingsml

Is there a more efficient way in processing an integer datatype?


I have the following piece of code:

datatype eInt = infinity of int | 0 | Int of int;

exception undefined;
fun eAdd(e1:eInt, 0:eInt) = e1
  | eAdd(0, e2) = e2
  | eAdd(e1, infinity) = infinity
  | eAdd(infinity, e1) = infinity
  | eAdd(infinity, ~infinity) = raise undefined
  | eAdd(~infinity, infinity) = raise undefined
  | eAdd(e1, e2) = e1 + e2;

There's a new datatype which allows for three types: infinity, 0, and int. I think 0 may be redundant here but I'm not all sure.

I used pattern matching to formulate the different types of possible results from adding the two eInts together.


There are four different outcomes.

  • If there's a 0, return other int
  • If there's a ∞ , return ∞
  • If there's a ∞ and -∞ , return undefined
  • Anything else, return the addition of the two of them

The only thing I can think of which makes this algorithm more efficient is if I were to remove the double cases, and at the end, run the algorithm again after reversing (e1, e2) to (e2, e1).

Any ideas on making this more efficient? I will be adding other operations such as division, which will have even more cases.


Solution

    1. Yes, 0 is redundant, since you also have Int 0.

    2. Use uppercase constructor names.

    3. You have not really said what you mean by Infinity of int. Judging from your examples, you are only interested in whether the infinity is positive or negative, so an int is quite redundant, too.

    4. Instead of using exceptions, use an option type.

    In summary, you might have

    datatype IntExt = PosInf
                    | NegInf
                    | Int of int
    
    fun extAdd (PosInf, i2) = if i2 = NegInf then NONE else SOME PosInf
      | extAdd (i1, PosInf) = if i1 = NegInf then NONE else SOME PosInf
      | extAdd (NegInf, _) = SOME NegInf
      | extAdd (_, NegInf) = SOME NegInf
      | extAdd (Int a, Int b) = SOME (Int (a+b))
    

    If you want an efficient implementation, consider encoding your integers as IEEE 754.