Monday, May 11, 2009

Factorial goofiness

It's Monday afternoon, and it's time for a silly post. Have you ever been browsing the Internet, looking at something completely code irrelevant, yet something struck you: "I bet I could do this in X language"? I saw a tshirt that said "factorial!", when something like that hit me.

Using some of the power of Scala, I'm going to make a factorial look like it does in math books. Meaning, when you see the phrase 4!, it should evaluate to 24. Well, let's just get a factorial function to work first.

scala> def fac(n: Int) : Int = if(n == 0) 1 else n * fac(n -1)
fac: (Int)Int

scala> fac(4)
res0: Int = 24

There's our logic! I want to use a bang operator though. I want it to be a "true" factorial resemblance. If I want a bang operator, I'll need to have my own class.

scala> class Fac(val i: Int) {
     | def fac(n: Int): Int = if(n == 0) 1 else n * fac(n - 1)
     | def ! = fac(i)
     | }
defined class Fac

scala> val test = new Fac(4)
test: Fac = Fac@1d9d55b

scala> test!
res1: Int = 24

Well, now. That's starting to look right, but there's still this thing: new Fac. I want to get rid of that as well. I mean, I just want to type 4!, and it will result in 24. This can be done through implicit conversions.

scala> implicit def int2Fac(n: Int) = new Fac(n)
int2Fac: (Int)Fac

scala> 4!
res2: Int = 24

And that's it! A pretty stupid example, but this example shows us several things:

  1. An example showing off operator overloading.
  2. An example showing optional periods and parenthesis in method calls.
  3. The reason for implicit conversions, and a perfect use case.

A fun example for a Monday.

-- Philip

No comments:

Post a Comment