More elegant coffeescript loop - coffeescript

JS:
for(i=this.current.arr.length;i<this.counterLength;i++){
dosomthing();
dosomethingelse();
}
COFFEE:
i = #current.arr.length
while i < #counterLength
dosomthing()
dosomethingelse()
i++
I know coffeescript has great loop syntax candy, but I can't find a more elegant way of writing it than this. Is there a more coffeescripty way of doing this?
I know about:
for currentArr in current.arr
//and
for currentArr, 1 in current.arr
but i needs to start at #currentLength and not 0

The [..] operator is what you are looking for:
start = this.current.arr.length
end = this.counterLength
for [start...end]
dosomthing()
dosomethingelse()
No need to predefine start and end, I just used it to make the code a bit clearer. Note that if start is greater then end, then it will go backwards.
Actually you need [...] operator, because you used < instead of <= in the code. The [...] operator excludes the last element.

Related

ObservableBuffer giving IndexOutOfBounds in Scala

I am mesmerized. The below code is giving me an indexoutofbound error. But if I were to delete the slashes enabling for(j <- i until tmpArray.length) it would work. I really do not understand why it is happening, and would appreciate an explanation.
for(i <- 0 until tmpArray.length)
{
// for(j <- i until tmpArray.length)
// {
if( date.getValue != null && tmpArray(i).date != date.getValue )
{
tmpArray.remove(i)
}
// }
}
You're modifying the array as you "iterate" over it.
You are actually iterating over the range 0 until tmpArray.length, which is calculated up front. At some point, you reduce the length of the array (or, I assume so, as I can't find remove on the Array class). But it's still going to continue the iteration up to whatever the last index was when you created the range.
When you uncomment the inner for block, you're making it recompute the range for each step of the outer for. And it just so happens that the j range will simply have nothing in it if i >= tmpArray.length. So it inadvertently guards against that failure.
This is very C-style (imperative) code. It looks like all you're trying to do is remove some items from an array. That's what filter is for.
val result = tmpArray.filter { d =>
if(date.getValue != null && d != date.getValue) false else true
}
This creates a new array (result) by passing an anonymous function to tmpArray.filter. It will pass each item in the array to your "predicate", and if it returns true, it'll keep that item in result, otherwise it will omit it.
You should note that I avoided saying "loop". Scala's for isn't for making loops. It's actually syntax sugar for calling methods like foreach and map. Google "scala for comprehensions" for more detail.
If you insist on creating a C-style loop using indexes and a loop variable, you'll want to use while, so that you can check if i < tmpArray.length each time.

isdigit function for BCPL

I am currently programming in BCPL for an OS course and wanted to write a simple is_digit() function for validation in a program of mine.
A code snippet of my current code follows:
let is_digit(n) be {
if ((n >= '0') /\ (n <= '9')) then
resultis true;
}
I am aware that BCPL has no notion of types, but how would I be able to accomplish this sort of thing in the language?
Passing in a number yields a false result instead of the expected true.
is_digit() is a function returning a value, rather than a routine, so should use = VALOF rather than BE. Otherwise, the code is OK.
let is_digit(n) = valof {
.....
resultis true
}
Functions that return values should be using valof rather than be, the latter (a routine rather than a function) can be called as a function but the return value you get back from it will be undefined(a).
In addition, you should ensure you return a valid value for every code path. At the moment, a non-digit will not execute a RESULTIS statement, and I'm not entirely certain what happens in that case (so best to be safe).
That means something like this is what you're after, keeping in mind there can be implementation variations, such as & and /\ for and, or {...} and $(...$) for the block delimiters - I've used the ones documented in Martin's latest manual:
LET is_digit(n) = VALOF {
RESULTIS (n >= '0') & (n <= '9')
}
(a) Since Martin Richards is still doing stuff with BCPL, this manual may help in any future questions (or see his home page for a large selection of goodies).

Why can't I use i++ in for loop in Swift

I know the difference between i++ and ++i in Swift. As the official document said, it is better to use ++i to increment i.
But I wonder why I get a syntax error using i++ in the for loop.
The code looks like this:
for var i = 0; i < 10; i++{
println("hello")
}
However, it is OK to use either i++ or ++i in other cases. Is there any restrictions in for loop?
The error says that:
Operator is not a known binary operator
The cause is very simple: you need to add a blank between the operator and the opening curly brace:
i++ {
^
without that, the compiler takes ++{ as a binary operator, with i and print("hello") as its arguments
The problem doesn't happen with the prefixed version of the increment operator because the i variable makes a clear separation between the ++ operator and the curly brace (letters and numbers cannot be used to define operators).

How to avoid return statement and escape from for loop?

I've been told to avoid use of return in Scala, although I'm not sure why.
I've got the following code, and it doesn't seem to return the proper thing unless I put the return keyword in there. Why do I need to put return?
def nextParen(chars: List[Char]): List[Char] =
for(i <- 0 to chars.size - 1) {
if(chars(i) == '(' || chars(i) == ')') {
return chars.slice(i, chars.size) // return HERE!
}
}
List.empty
}
The argument for avoiding return is that it leads to code that is less readable, and not refactor-safe. It's not an absolute rule, if you find an algorithm that's best expressed that way, but usually code can be made clearer by writing it as an expression.
This particular code looks to be equivalent to:
def nextParen(chars: List[Char]) =
chars.dropWhile{c => c != '(' && c != ')'}
In general, try to focus on writing expressions rather than procedures; rather than telling the compiler what steps it should take, tell it what the value is. Even if you didn't know about dropWhile, you could write the loop as a fold (e.g. foldLeft) that says what to do at each element of the list, and then the case where the list is empty at the end would fall out naturally, rather than needing two different branches for where there is a match and where there isn't.
There's nothing wrong with using return when it clearly expresses your intent in a good algorithm. However, you should be cautious about using it because it isn't necessary, and most things you want to do already have decent implementations in the collections library.
So, for example, your code works but is O(n^2) in the size of the list because you're indexing into a linear data structure. It's much better to use
chars.dropWhile(c => c != '(' && c != ')')
or if you don't know about that, any of a huge number of alternatives:
val i = chars.indexWhere(c => c == '(' || c == ')')
if (i < 0) chars take 0 else chars drop i
var found = false
chars.filter(c => found || { found = (c == '(' || c == ')'); found })
You can probably come up with half a dozen more without trying too hard. (Fold with an indicator, for/yield with an if clause, span, etc.)
So the best reason to not use return is that you should know your library. Usually you don't need it; it's better to use a stock method that computes what you want.
You are using a for in the imperative sense above. You don't have to use a return if you use it in a more functional sense i.e., as a for-yield or fold or takeWhile.
I think one of the biggest thing to wrap your head around when you move from imperative to functional (side-effect free) is the notion that you can express your code a sequence of expressions, each of which evaluates to a value. For example, a for-yield expression evaluates to a value. So in an imperative world you are executing a sequence of statements that is changing the state (data structures, console etc) around you.
PS: I've used a lot of terms (e.g., side-effect, for-yield, value) that may sound unfamiliar to a new Scala programmer. But with more experience they will make more sense. I would highly recommend this book - Structure and Interpretation of Computer Programs

validate a where clause query in c#

I was asked this question in an interview.
Write a c# program which will print out all the errors in a statement.
(a + b == 3 and x == y or b / c == d)
Allowed keywords are and/or, braces are allowed and have to match. The statement has to be logically correct. Print out all the errors.
Something like a compiler or sql analyzer.
Any idea how to go about syntax checking?
You're being asked to build a parser.
The computer science theory behind compilers is extensive and complex. To keep it simple, I recommend reading Jack Crenshaw's compiler tutorial. It will show you in the first few chapters how to do exactly this by building a top-down recursive descent parser. His example is almost exactly what you're trying to do. It's in Pascal, but it's still easy enough to follow and the concept still applies.
Google for "jack crenshaw let's build a compiler", or browse to:
http://compilers.iecc.com/crenshaw/
That's actually pretty complicated if you want to get it 100% right. The direction to research would have to do with the keywords "finite state automata", "regular expressions" (not to be confused with Regex) and "context-free grammars". Also there's an approach called "recursive descent parser" but you'll need to understand the above concepts first.
Matching brackets and parenthesis is easy.
string expression = "(a + b + (c + d) )";
int brackets = 0;
int parenthesis = 0;
foreach(char c in expression)
{
if(c == '(') ) parenthesis++;
if(c == ')') ) parenthesis--;
if(parenthesis < 0) { // ERROR!!! }
// Same logic with brackets
}
if (parenthesis != 0) { ERROR!!! }
Also, I would use a similar approach with "statements mergers" ( +, -, *, / ) and "statements comparators" ( ==, !=, <, <=, ... )
For each word in your expression, only a few valid keywords can follow.
As it was mentionned before, writing parsers is a difficult task, planning every exception case right away is hardly possible. This should be the general idea instead of a definitive solution.
On a final note, it is perfectly ok to have multiple passes to scan for different things. First pass is brackts/parenthesis only, then check for something else in another loop.