Learn You Scala for Great Good!

Learn You Scala for Great Good!

I came to Scala from Java. So when I wanted to learn Scalaz, I didn’t know what to start with. I decided that the best way would be to start with functional programming. It’s strange but the best manual was Learn You a Haskell for Great Good!

Yes, I chose my way: I started learning Haskell in order to know Scala better!

For better understanding I started to “translate” Haskell examples into Scala. Now I have decided to publish these examples.

Guards, guards!

We’re going to make a simple function that berates you differently depending on your BMI (body mass index). Your BMI equals your weight divided by your height squared. If your BMI is less than 18.5, you’re considered underweight. If it’s anywhere from 18.5 to 25 then you’re considered normal. 25 to 30 is overweight and more than 30 is obese. So here’s the function (we won’t be calculating it right now, this function just gets a BMI and tells you off)

Guards are indicated by pipes that follow a function’s name and its parameters. Usually, they’re indented a bit to the right and lined up. A guard is basically a boolean expression. If it evaluates to True, then the corresponding function body is used. If it evaluates to False, checking drops through to the next guard and so on. If we call this function with 24.3, it will first check if that’s smaller than or equal to 18.5. Because it isn’t, it falls through to the next guard. The check is carried out with the second guard and because 24.3 is less than 25.0, the second string is returned.


    bmiTell :: (RealFloat a) => a -> a -> String  
    bmiTell weight height  
        | weight / height ^ 2 <= 18.5 = "You're underweight, you emo, you!"  
        | weight / height ^ 2 <= 25.0 = "You're supposedly normal. Pffft, I bet you're ugly!"  
        | weight / height ^ 2 <= 30.0 = "You're fat! Lose some weight, fatty!"  
        | otherwise                 = "You're a whale, congratulations!"  

 

I “translated” this code into Scala and you can see the result:


def rate(w:Int, h:Double):String = {
  val ratio = w/pow(h,2)
  ratio match {
    case r if r <= 18.5 => s"Underweight $r"
    case r if r <= 25 => s"Normal $r"
    case r if r <= 30 => s"Overweight! $r"
    case r => s"Whale! $r"

  }
}

println(rate(78, 1.76))

Guards in Scala use the keyword if. Instead of an otherwise-clause, you simply specifiy the pattern without a guard. Pattern matching mechanism is working well.
Both examples look very similar.

 

To be continued

Please follow and like us:

About Alexandre Kremlianski

Scala / Scala.js / JavaScript programmer

Leave a Reply

Your email address will not be published. Required fields are marked *