I really like this:
var value = maxValue > minValue ? minValue : maxValue;
Is there something equally concise in Coffescript?
value = if maxValue > minValue then minValue else maxValue
There is a more concise option in both javascript and coffeescript :)
value = Math.min(minValue, maxValue)
As Răzvan Panda points out, my comment may actually one of the better answers:
value = `maxValue > minValue ? minValue : maxValue`
This is a case where it feels like CoffeeScript has competing philosophies:
Be concise
Don't be redundant
Since all operations return a result, the if/then/else way of doing things gives you what you need. Adding the ?/: operator is redundant.
This is where I wish they'd give us the ?/: ternary operator even though it is redundant... it simply reads better than the if/then/else variant.
Just my 2c.
You can write it like this:
value = if maxValue > minValue then minValue else maxValue
It will compile like your code.
Below is the fact:
In the documentation, there's a section titled "Conditionals, Ternaries, and Conditional Assignment". This leads one to believe that coffeescript supports
condition ? when-true : when-false
but in fact it does not.
Below is the information about the patch which will solve this issue
Here's the patch (and it's pushed to coffeescript.org):
http://github.com/jashkenas/coffee-script/commit/ec2d358ae3c82e9888c60695d7cce05edde0c55a
Examples:
mood = greatlyImproved if singing
if happy and knowsIt
clapsHands()
chaChaCha()
else
showIt()
date = if friday then sue else jill
options or= defaults
value = maxValue > minValue && minValue || maxValue
This is actually not correct, check the comments.
Related
I've been coding for about 2 years, but I am still terrible at it. Any help would be much appreciated. I have been using the following code to set my background image parameters, after updating to Xcode 7.3 I got the warning 'C-Style statement is deprecated and will be removed':
for var totalHeight:CGFloat = 0; totalHeight < 2.0 * Configurations.sharedInstance.heightGame; totalHeight = totalHeight + backgroundImage.size.height {...}
Just to clarify, I have looked at a few other solutions/examples, I have noticed that one workaround is to use the for in loop, however, I just can't seem to wrap my head around this one and everything I have tried does not seem to work. Again, any help would be much appreciated.
A strategy that always works is to convert your for loop into a while loop along the lines of this pattern:
for a; b; c {
// do stuff
}
// can be written as:
a // set up
while b { // condition
// do stuff
c // post-loop action
}
So in this case, your for loop could be written as:
var totalHeight: CGFloat = 0
while totalHeight < 2.0 * Configurations.sharedInstance.heightGame {
// totalHeight = totalHeight + backgroundImage.size.height can be
// written slightly more succinctly as:
totalHeight += backgroundImage.size.height
}
But you're right, the preferred solution when possible is to use for in instead.
for in is a bit different to the C-style for or while. You don't control the loop variable directly yourself. Instead, the language will loop over any values produced by a "sequence". A sequence is any type that conforms to a protocol (SequenceType) that can create a generator that will serve that sequence up one by one. Lots of things are sequences – arrays, dictionaries, index ranges.
There's a kind of sequence called a stride that you could use to solve this particular problem using for in. Strides are a bit like ranges that increment more flexibly. You specify a "by" value that is the amount to vary by each time around:
for totalHeight in 0.stride(to: 2.0 * Configurations.sharedInstance.heightGame,
by: backgroundImage.size.height) {
// use totalHeight just the same as with the C-style for loop
}
Note, there are two ways of striding, to: (up to but not including, like if you'd used <), and through: (up to and including, like <=).
One of the benefits you get with a for in loop is that the loop variable doesn't need to be declared with var. Instead, each time around the loop you get a fresh new immutable (i.e. constant) variable, which can help avoid some subtle bugs, especially with closure variable capture.
You still need the while form occasionally (for example there's no built-in type that allows you to double a counter each time around), but for much everyday use there's a neat (and hopefully more readable) way of doing it without.
Might be best to go with a while loop:
var totalHeight: CGFloat = 0
while totalHeight < 2.0 * Configurations.sharedInstance.heightGame {
// Loop code goes here
totalHeight += backgroundImage.size.height
}
I want to write a binary search program in Scala without using any if-else statements at all. Basic strategy which i have devised uses the return value of comparison between array[mid] and search_key. In short :
1) Generate return value based on comparison between array[mid] and search_key
2) Create a unique string using that return value.
3) Call function using 'reflection' with help of that string
So my question is ...is there any computational logic which returns different values in this case ? How can i achieve this ? For example :
if array[mid] == search_key , return 0
if array[mid] > search_key , return 1
if array[mid] < search_key , return 2
If anyone have any better solution for this problem, please also suggest that.
The easy way that does something similar is
array(mid) compareTo search_key
This line is equivalent to
if (array(mid) == search_key) 0
else if (array(mid) < search_key) -1
else 1 // if (array(mid) > search_key)
As for the best way to do it, you could make a sequence of actions to take, and compute an index into that sequence. If you are interested you can see the full code in https://gist.github.com/kolmar/bcfc94ee4051ee7eb3a1
I'm new to CoffeeScript and have been reading the book, The Little Book on CoffeeScript. Here are a few lines from the book's Chapter 2 which confused me while reading :
The only low-level loop that CoffeeScript exposes is the while loop. This has similar behavior to the while loop in pure JavaScript, but has the added advantage that it returns an array of results, i.e. like the Array.prototype.map() function.
num = 6
minstrel = while num -= 1
num + " Brave Sir Robin ran away"
Though it may look good for a CoffeeScript programmer, being a newbie, I'm unable to understand what the code does. Moreover, the words returns an array of results doesn't seem to go together with the fact that while is a loop construct, not a function. So the notion of it returning something seems confusing. Furthermore, the variable num with the string "Brave Sir Robin ran away" in every iteration of the loop seems to be awkward, as the value num is being used as the loop counter.
I would be thankful if you could explain the behavior of the code and perhaps illustrate what the author is trying to convey with simpler examples.
Wow! I didn't know that but it absolutely makes sense if you remember that Coffeescript always returns the last expression of a "block".
So in your case it returns (not via the "return" statement if that is what confuses you) the expression
num + " Brave Sir Robin ran away"
from the block associated with the while condition and as you will return multiple such expressions it pushes them on an array.
Have a look on the generated JavaScript and it might be clearer as the generated code is pretty much procedural
var minstrel, num;
num = 6;
minstrel = (function() {
var _results;
_results = [];
while (num -= 1) {
_results.push(num + " Brave Sir Robin ran away");
}
return _results;
})();
I hope that makes sense to you.
Beware, that function call can be very inefficient!
Below is a prime factors generator
'use strict'
exports.generate = (number) ->
return [] if number < 2
primes = []
candidate = 1
while number > 1
candidate++
while number % candidate is 0
primes.push candidate
number /= candidate
candidate = number - 1 if Math.sqrt(number) < candidate
primes
This is the version using while as expression
'use strict'
exports.generate = (number) ->
return [] if number < 2
candidate = 1
while number > 1
candidate++
primes = while number % candidate is 0
number /= candidate
candidate
candidate = number - 1 if Math.sqrt(number) < candidate
primes
First version ran my tests in 4 milliseconds, the last one takes 18 milliseconds. I believe the reason is the generated closure which returns the primes.
for s=1:length(C_tem)
for w=1:length(C_tem{s})
if (abs(C_tem{s}{w}) >= 0)
C_tem{s}{w} = 1;
else
C_tem{s}{w} = 0;
end
end
end
I am trying to set the values larger than 0 to 1, and if less or equal to 0, but for some reason this doesn't work.
I'm new in matlab, and I really need the help if possible. Thank you in advance..
i havn't worked on matlab much but this part of code feels suspicious -
if (abs(C_tem{s}{w}) >= 0)
C_tem{s}{w} = 1;
else
C_tem{s}{w} = 0;
end
Why are you doing abs here? I think it will remove sign from number. Code should be something like this-
if (C_tem{s}{w} > 0) //I have removed abs and >= is replaced with >
C_tem{s}{w} = 1;
else
C_tem{s}{w} = 0;
end
abs(x)>=0 is true for all values of x. The simple answer is to remove the abs. The more complete answer follows up on Dan's comment. The cell array is unnecessary at the inner level. If you instead had a cell array of regular arrays, then you could do this for the entire block of code.
for s=1:length(C_tem)
C_tem{s} = (C_tem{s} >= 0);
end
Two things to notice: comparison operators are vectorized, meaning they return a matrix of the same size as the input, thus comparing all values at once. And, the output of the operator is 1 where true and 0 where false.
Also look at the builtin function sign to see if that's closer to what you want to do.
I really like this:
var value = maxValue > minValue ? minValue : maxValue;
Is there something equally concise in Coffescript?
value = if maxValue > minValue then minValue else maxValue
There is a more concise option in both javascript and coffeescript :)
value = Math.min(minValue, maxValue)
As Răzvan Panda points out, my comment may actually one of the better answers:
value = `maxValue > minValue ? minValue : maxValue`
This is a case where it feels like CoffeeScript has competing philosophies:
Be concise
Don't be redundant
Since all operations return a result, the if/then/else way of doing things gives you what you need. Adding the ?/: operator is redundant.
This is where I wish they'd give us the ?/: ternary operator even though it is redundant... it simply reads better than the if/then/else variant.
Just my 2c.
You can write it like this:
value = if maxValue > minValue then minValue else maxValue
It will compile like your code.
Below is the fact:
In the documentation, there's a section titled "Conditionals, Ternaries, and Conditional Assignment". This leads one to believe that coffeescript supports
condition ? when-true : when-false
but in fact it does not.
Below is the information about the patch which will solve this issue
Here's the patch (and it's pushed to coffeescript.org):
http://github.com/jashkenas/coffee-script/commit/ec2d358ae3c82e9888c60695d7cce05edde0c55a
Examples:
mood = greatlyImproved if singing
if happy and knowsIt
clapsHands()
chaChaCha()
else
showIt()
date = if friday then sue else jill
options or= defaults
value = maxValue > minValue && minValue || maxValue
This is actually not correct, check the comments.