October 2013

Taken from here. Note that whether torture can work is not the same question as whether we should do it. (more…)

I’ve heard a bit about Scala*, but I’m still very much a complete newbie. The languages I’m most familiar with are Java (along with C#/C++/C) and Python, so I’m treating it as a sort of mixture of the two. Messing about in an interactive tutorial I got to a section treating the interpreter as a calculator. In a regular handheld calculator dividing two integers commonly results in a decimal, but in a programming language (like Scala) where those are completely different “types”, it’s likely to round the result into another integer. So to use math theory speak, integers are closed under division, their “domain” is equal to their “image”, “range” or “codomain”. I decided to try changing that (should the verb be “opening”? “unclosing”?). I noticed that the Int class has a toDouble method, and sure enough Double does as well. I hoped that ducktyping by itself would be sufficient, but unfortunately what would be a primitive in Java is merely an Any in Scala, and when I tried ducktyping it insisted they needed to be AnyRef instead (analogous to an Object in Java). Fortunately, implicit classes allow us to treat them otherwise.

implicit class SuperInt(val i:Int) extends AnyRef {      
  def toDouble = i.toDouble     
implicit class SuperDouble(val d:Double) extends AnyRef {      
  def toDouble = d.toDouble     
def divide( numerator: {def toDouble:Double },
            denominator: {def toDouble:Double }) = {  

The divide function works the same whether you pass in an Int or Double. Doing some googling, I found that implicitly converting Any to AnyRef is frowned upon in Scala, but I’m way too ignorant to know the reasons, having only found out they were different things from the same people doing the frowning. Those who know why, or who have suggestions for the right (what’s analogous to “Pythonic”?) way to do things are welcome to chime in.

*I don’t think Steve Yegge’s ideological ranking of languages was the first place, but it’s entertaining enough to link. And yes, annoyance with the “liberalism” of one language (JavaScript) did inspire me look up something in the opposite direction. Although I still don’t actually know what about Scala makes it more “conservative” than the C family.

I was familiar with the phenomena of two (or more) different people making the same scientific discovery around the same time. I wasn’t familiar with the name though. A handy thing to refer to.