0

I have two functions that find the factorial of a number and one works using integers, but the second using only shorts yield an error. This is the code

var fac16i: Function2[Short, Short, Short] = new Function2[Short, Short, Short] {
    @tailrec override def apply (x: Short, acc: Short = 1): Short = {
      if (x.toShort <= 1.toShort) acc.toShort
      else apply(x - 1, x  * acc)
    }
  }

  var fac32i: Function2[Int, Int, Int] = new Function2[Int, Int, Int] {
    @tailrec override def apply (x:Int, acc:Int=1): Int = {
      if (x<=1) acc
      else apply(x-1, x * acc)
    }
  }

Can someone help me with this. Note: I am using scala-native.

Lambda Banquo
  • 81
  • 1
  • 5
  • 1
    Multiplication of **Shorts** return **Int**, this is also true in Java. Not sure what the rationale is, but probably since the multiplication of two **Shorts** can easily overflow a **Short** than it makes sense to return an **Int** _(it may also be a limitation of CPUs but no idea)_ - In any case, given Factorial is a function that can easily overflow **Ints** what is the point of having a **Short** version? You usually will use **Longs** or even **BigInts** for Factorial. - Finally. aby reason for implementing your functions by creating an anonymous instance instead of a literal or a `def` – Luis Miguel Mejía Suárez Nov 25 '20 at 00:31
  • You are my hero. – Lambda Banquo Nov 25 '20 at 00:36

1 Answers1

2

Move the .toShort casting from where it's not needed to where it is needed.

if (x <= 1) acc
else apply((x-1).toShort, (x*acc).toShort)
jwvh
  • 50,871
  • 7
  • 38
  • 64