In JavaScript we can test for the presence of a named property in an object using the in operator:
var obj = { foo: 123, bar: 0 };
'foo' in obj; // => true
'bar' in obj; // => true, handy since "obj.bar" is falsey.
'gah' in obj; // => false
However, in CoffeeScript, the in operator is overloaded to perform an array search (presumably to prevent misuse of for...in), so we cannot use it as above. Instead it seems like we must do a linear search for a named property in the object's list of keys:
obj = { foo: 123, bar: 0 }
'foo' in Object.keys(obj) # true, but O(n) search instead of likely O(1).
Is there a better (more efficient, more concise) way to test for the existence of a named property in an object in CoffeeScript?
use of :
obj ={foo:13}
(foo of obj) == true
Related
def checkHappynumber(n: Int): Boolean = {
val set = scala.collection.mutable.HashSet[Int]()
var num: Int = n
while(num != 1) {
var newnum: Int = 0
while (num != 0) {
newnum += (num % 10) * (num % 10)
num /= 10
}
if(!set.add(newnum)){
return false;
}
num = newnum
}
return true
}
What's "!" role in there? the if(!set.add(newnum))? I know that hashset can't have repeated value. The only question is how "!" works here.
In Scala, !foo is syntactic sugar for foo.unary_!. In other words, !foo is just calling the method named unary_! just like foo.bar is calling the method bar. There is nothing special about unary_! in that regard.
In your case, this means that !set.add(newnum) is just syntactic sugar for set.add(newnum).unary_!.
Like with all other methods, if you want to know what the method does, you first need to find where it is defined. In this case, the return type of scala.collection.mutable.Set.add is scala.Boolean which means the specific method being called is scala.Boolean.unary_!, which is defined like this:
def unary_!: Boolean
Negates a Boolean expression.
!a results in false if and only if a evaluates to true and
!a results in true if and only if a evaluates to false.
Returns: the negated expression
! is a negation operator (!true is false, !false is true). HashSet.add returns true if element was not present in the set (successfully added), false otherwise. This code returns false if element was already present in the hashset (trying to add it for the second time).
Here's documentation of add method.
In scala we can use for loops as follows:
for { a <- someCollection
b = a.someFunc} //inbody we can use b
I need similar functionality with a while loop for example:
while({ val a = someFunction
a.isDefined }) { //do something with a in body }
How can I do this in scala?
EDIT
I know we can do this using a var on top and modifying it within the loop but I was looking for something more elegant.
What I wish to accomplish is as follows. The function someFunction iterates over a collection of Options and check for the item that is not a None. If it does not find such an option it returns a None. I can probably do this using
for( a <- myCollection
if a.isDefined) {}
but in this case I dont make use of my function.
You could write your own extended while function, like:
def extendedWhile[T](condFunc: => Option[T])(block: T => Unit): Unit = {
val a = condFunc
if (a.isDefined) {
block(a.get)
extendedWhile(condFunc)(block)
}
}
Which can be used as:
def rand =
if ((new scala.util.Random).nextFloat < 0.4) None
else Some("x")
extendedWhile(rand) {
x => println(x)
}
// prints out x a random amount of times
This extendedWhile function is tail recursive, so it should normally be as performant as the regular while loop.
I am not sure I like this, but one way to do this is to define the variable as 'var' outside the loop.
var a: Boolean = _;
def someFunction: Boolean = true
while({ a = someFunction; a }) {
println("hi " + a)
}
For is actually syntactic sugar for foreach, map, and flatMap.
So your code above desugars to:
someCollection.map { a=> f(a)}.foreach {b => ... //something using b}
Now, while is not a desugaring, but an actual imperative syntactic construct.
So the best you can do is
var a = true
while (a) {
a = someFunction (a)
}
In practice I never find myself using while, and instead use higher-order functions: like
input.takeWhile(_ != '').foreach { //do something }
Apologies if this is a newbie question...
In Scala I understand that it is preferred to use an Option rather than returning null when you have a function which returns an instance but could potentially return nothing. I understand that this makes it better with regards to safety, because you are not passing null references around, and risking NullPointerException somewhere down the line.
However, is there a cleaner way to handle options than using pattern matching?
The syntax I end up using is the following:
val optObj : Option[MyObject] = myFunctionThatReturnsOption
optObj match {
case Some(obj) => {
//my code using obj
}
case None => _
}
In reality all this doing is the equivalent of the Java version:
MyObject obj = myMethodThatCanReturnNull()
if (obj != null) {
//my code using obj
}
Is there some other way to avoid all this boilerplate in Scala when using Option instead of null references? All I want to do is execute a piece of code as long as the Option contains some object (i.e. is not None).
Use foreach, getOrElse and/or map if you want to work in a more consistent way. Here's some use cases and what I'd do:
//I want to get a non-null value and I have a sane default
val result = myOption getOrElse 3
//I want to perform some side effecting action but only if not None
myOption foreach{ value =>
println(value toString ())
}
//equivalently
for(value <- myOption){
//notice I haven't used the "yeild" keyword here
}
//I want to do a computation and I don't mind if it comes back as an Option
val result = for(value <- myOption) yield func(value)
val equivalent = myOption map func
The third example will use map in both cases.
It gets really interesting when you can mix and match things in a "for comprehension" (Google term.) Let's say that func also returns an Option but I only want things working in specific cases:
val result = for{
value <- myOption if value > 0
output <- func(value)
} yield output
Now I get back an Option but only if myOption contained an integer that was greater than zero. Pretty nifty stuff, no?
You can use foreach if you just want to perform some side-effecting operation with the value:
optObj.foreach(obj => {
//my code using obj
})
if you have some other use case you should use some other method on Option like map, filter or getOrElse.
Of course, the way I usually use options if I only care about present value is foreach:
optObj.foreach { obj =>
//...
}
Having said this, there are a lot of other options (which #wheaties enlisted) and some people keep battling about the true one.
You can use the flatMap-method pretty well with Option. Like hier:
case class Player(name: String)
def lookupPlayer(id: Int): Option[Player] = {
if (id == 1) Some(new Player("Sean"))
else if(id == 2) Some(new Player("Greg"))
else None
}
def lookupScore(player: Player): Option[Int] = {
if (player.name == "Sean") Some(1000000) else None
}
println(lookupPlayer(1).map(lookupScore)) // Some(Some(1000000))
println(lookupPlayer(2).map(lookupScore)) // Some(None)
println(lookupPlayer(3).map(lookupScore)) // None
println(lookupPlayer(1).flatMap(lookupScore)) // Some(1000000)
println(lookupPlayer(2).flatMap(lookupScore)) // None
println(lookupPlayer(3).flatMap(lookupScore)) // None
Here's a great reference for Scala best practices regarding options:
http://blog.tmorris.net/posts/scalaoption-cheat-sheet/index.html
If I have a class that I pass a number of parameters to:
class Foo
constructor: (parameters) ->
#bar = parameters.bar
#moo = parameters.moo
The class is created like so:
foo = new Foo(bar: 2, moo: 8)
My question is what is the most elegant way to detect in the constructor if the variables being passed exist, and if not to set a default. The way I would do it in javascript would be:
this.bar = ( parameters.bar !== undefined ) ? parameters.bar : 10;
where 10 is the default.
Thanks for your help :)
Good answers - Just to summerize the best:
Inorder to detect if a parameter exists and define a default if it doesn't, in javascript is:
this.bar = ( parameters.bar !== undefined ) ? parameters.bar : 10;
and in coffescript is:
#bar = parameters.bar ? 10
So elegant and compact!
You can use the existential operator:
class Foo
constructor: (options = {}) ->
#bar = options.bar ? 10
#moo = options.moo ? 20
That constructor compiles to:
// Compiled JS.
function Foo(options) {
var _ref, _ref1;
if (options == null) {
options = {};
}
this.bar = (_ref = options.bar) != null ? _ref : 10;
this.moo = (_ref1 = options.moo) != null ? _ref1 : 20;
}
An equivalent alternative is to destruct the options object immediately (therefore avoiding an unnecessary name for it) and then setting the default values in case those options were not passed:
class Foo
constructor: ({#bar, #moo} = {}) ->
#bar ?= 10
#moo ?= 20
As passing an object with options is a common pattern in JS code, some libraries have useful utility functions that can help with this. Underscore, for example, provides _.defaults, which i think results in quite readable code:
class Foo
constructor: ({#bar, #moo} = {}) ->
_.defaults #, bar: 10, moo: 20
If you are not using Underscore, there is also $.extend (who doesn't use jQuery anyway?):
class Foo
defaults = bar: 10, moo: 20
constructor: (options = {}) ->
{#bar, #moo} = $.extend {}, defaults, options
An alternative is to extend the Foo object directly if you trust that the only options that will be passed are the valid ones (this results in quite minimal JS compared to the other ones):
class Foo
defaults = bar: 10, moo: 20
constructor: (options = {}) ->
$.extend #, defaults, options
And a final alternative is to have the default values in the Foo.prototype and only set them as own properties if they come in the options parameter:
class Foo
bar: 10
moo: 20
constructor: ({bar, moo} = {}) ->
#bar = bar if bar?
#moo = moo if moo?
This prevents all the instances of Foo from having separate properties of their own and instead shares the same properties between instances when they use the default values, the same that is usually done with methods. You can also do #bar = bar if #bar isnt bar to assign those properties only when the parameter value differs from the default value.
As you can see, there are quite a lot of ways to do this. None of them is perfect, they all have their pros and cons, so try to choose the one that better suits your needs/taste/whatever =D
You could do this using the ?= operator:
class Foo
constructor: (parameters) ->
#bar = parameters.bar
#bar ?= 10
#moo = parameters.moo
#moo ?= 20
If you didn't mind passing in positional arguments rather than a hash, you could also do this very elegantly using default parameter values:
class Foo
constructor: (#bar = 10, #moo = 20) ->
f = new Foo
You could define an object of defaults and do something like this..
(parameters = {}) ->
this[key] = parameters[key] ? defaults[key] for key, value of defaults
But you really don't have to go through all of that. The easiest way to make default values is just to use prototypal inheritance...
class Foo
bar: 10
moo: 10
constructor: (parameters = {}) ->
this[key] = value for own key, value of parameters
Assuming the above:
a = new Foo();
a.bar # => 10
b = new Foo(bar: 50)
b.bar # => 50
With the exception of the constructor every property you define with a : will become a property on the object's prototype.
The class definition translates to this JavaScript:
Foo = (function() {
Foo.prototype.bar = 10;
Foo.prototype.moo = 10;
//etcetc
return Foo;
})();
Play with it. Hope that helps.
There is a more simpler way:
class Foo
constructor: (parameters = {}) ->
{
#bar = 10
#moo = 20
} = parameters
The new version of coffeescript has a great way to solve this exact problem
class MyObject
constructor: ({string1='x', string2='y'} = {})
it works great with regular functions too
myFunction = ({string1='x', string2='y'} = {}) ->
string1 + string2
console.log myFunction({string1:"a", string2:"b"})
# outputs: 'ab'
console.log myFunction()
# outputs: 'xy'
I have the following code in Scala-IDE:
type myF = () => Boolean
def acceptFunction(f: myF) {
//...
}
and then:
var a = false
def isA = () => a
but when I try passing it, to the acceptFunction, it results in error:
acceptFunction(isA)
the error is:
type mismatch; found : () => Boolean required: Boolean
But why?
If I declare isA like this:
def isA() = () => a
then it is accepted, but I assume, it get's evaluated because of the parenthesis.
Is there any way to pass such a function for furhter evaluation?
UPDATE:
Looks like it is something with Scala-IDE. The REPL has no problems with these expressions. However, still I can't make it so that the passed function does not get turned into a closure. I mean, that it turns into closure, and changing the var a later and calling the example with println(f()) again - does not change the value. So, the second part of the question remains - is there any way to pass such a function for furhter evaluation?
Are you sure you didn't make a mistake when writing your code the first time? I copied and pasted what you had into the 2.9.1 REPL and it worked fine.
scala> type myF = () => Boolean
defined type alias myF
scala> var a = false
a: Boolean = false
scala> def isA = () => a
isA: () => Boolean
scala> def acceptFunction(f: myF) {println(f())}
acceptFunction: (f: () => Boolean)Unit
scala> acceptFunction(isA)
false
scala>
UPDATE: isA is a closure when you define it. Passing it to acceptFunction has no effect on whether it grabs a.
Is your purpose to write a function, acceptFunction, which takes a function, f, which captures an external value, a, at the time it's defined?
You could do that like so:
// Defines a function which returns a function with returns the
// value that was captured at the outer function's call time.
def isB = { (b: Boolean) => { () => b }: myF }
a = true
val f = isB(a)
acceptFunction(f) // >> true
a = false
acceptFunction(f) // >> true
Is that where you're trying to go?