Author | Message |
---|---|
jpascua
Posts: 197
|
Posted 16:09 Oct 19, 2014 |
I'm trying to do assignment #2 but I have no clue of how to get started. I took notes of everything the professor wrote on the board in class last Thursday and did the best in my ability to understand what he was explaining. However, now that I go back to them, they don't make sense. So the exercise wants us to create a set with the signature def singletonSet(elem: Int): Set. What I have written in notes is: def singletonSet(elem: Int) = (x: Int) => x == elem. This doesn't make much sense to me. If anyone can help me get started, I would greatly appreciate it. Last edited by jpascua at
16:13 Oct 19, 2014.
|
wsakura
Posts: 64
|
Posted 20:28 Oct 19, 2014 |
I'm not sure if I get this 100% either, but from what I understand, in this: Given: which is a "Set" function that has nothing to do with the "Set" in scala. This is a function that takes in and integer and tests a boolean statement. For: def singletonSet(elem: Int) = (x: Int) => x == elem ***Set = (x: Int) => x == elem is similar to our Set function "Set = Int => Boolean"*** what's happening is that you're defining a function named "singletonSet", which takes in an Integer named "elem". This: (x: Int) => x == elem , declares that if x == elem, then that should be the only element in the set because if there is only one element "x" in the set and x == elem, then elem is in the set. You can test this with his example of: println( contains(singletonSet(1), 1) )
I'm not sure if all this is correct, so please correct me if I'm wrong. Hope this helps. |
jpascua
Posts: 197
|
Posted 22:36 Oct 19, 2014 |
I managed to try this out. It works. However I don't quite understand why it does. Also, are we supposed to be doing this on a worksheet or on an actual Scala file? |
wsakura
Posts: 64
|
Posted 01:09 Oct 20, 2014 |
I used a Scala file, but I think you can do it on a worksheet. I haven't tried it yet, however. From what I understand, it seems to work because it's as though we're creating an empty function and initializing it after. So, for instance: String randomString = new String(); seems to be similar to type Set = Int => Boolean (so Set is initialized to (Int => Boolean)) Then when we use: def singletonSet(elem: Int): Set = (x: Int) => x == elem def singletonSet(elem: Int): Set is similar to public Set singleton(int elem) and it's as though we're initializing Set = a => b, where a is (x: Int) and b is (x == elem) Last edited by wsakura at
01:09 Oct 20, 2014.
|