reset password
Author Message
Anon
Posts: 134
Posted 13:08 Oct 08, 2013 |

I understand that we are defining sets as functions, not as a list of integers. The function (the set) will tell you if the element is in the set, it doesn't search some array, I get that. What I'm finding difficult is implementing with scala syntax. I read the FAQ on Coursera and the explanation on the wiki page as well as other material online (over the course of several days), but I'm still having a hard time grasping how to implement. Anybody else on this boat?

Are there any resources that I haven't mentioned anybody knows of that can help? Maybe some practice problems similar to this?

Thanks

rabbott
Posts: 1649
Posted 21:10 Oct 08, 2013 |

Can you say more about the problems you are having. Here is a function that represents the set of even numbers.

def evens(n: Int): Boolean =   n % 2 == 0

The idea is as simple as that.

The preceding may look more familiar as follows.

def evens(n: Int): Boolean = {

n % 2 == 0

}

It's the same function either way.

Here's a function that characterizes the positive perfect squares. This shows it run in a worksheet.

def positivePerfectSquares(n: Int): Boolean = {
  if (n < 0) false
  else {
    // round is used in case the sqrt function produces an answer
    // that's a little below the square root, e.g., 2.9999999999
    // for sqrt(9). But round returns a long so toInt is needed.

    val sqrtRoot: Int = math.sqrt(n).round.toInt
    sqrtRoot * sqrtRoot == n
  }
}                                  //> positivePerfectSquares: (n: Int)Boolean

positivePerfectSquares(25)         //> res2: Boolean = true
positivePerfectSquares(32)         //> res3: Boolean = false

 

Last edited by rabbott at 21:48 Oct 08, 2013.