Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if int is between two numbers

Why can't do you this if you try to find out whether an int is between to numbers:

if(10 < x < 20) 

Instead of it, you'll have to do

if(10<x && x<20) 

which seems like a bit of overhead.

like image 604
Timo Willemsen Avatar asked Jan 02 '10 21:01

Timo Willemsen


People also ask

How do you check if a value is within a range in JavaScript?

const inRange = (num, num1, num2) => Math. min(num1, num2) <= num && Math. max(num1, num2) >= num; Could be like this if you want to make inRange inclusive and not depend on order of range numbers (num1, num2).


2 Answers

One problem is that a ternary relational construct would introduce serious parser problems:

<expr> ::= <expr> <rel-op> <expr> |            ... |            <expr> <rel-op> <expr> <rel-op> <expr> 

When you try to express a grammar with those productions using a typical PGS, you'll find that there is a shift-reduce conflict at the point of the first <rel-op>. The parse needs to lookahead an arbitrary number of symbols to see if there is a second <rel-op> before it can decide whether the binary or ternary form has been used. In this case, you could not simply ignore the conflict because that would result in incorrect parses.

I'm not saying that this grammar is fatally ambiguous. But I think you'd need a backtracking parser to deal with it correctly. And that is a serious problem for a programming language where fast compilation is a major selling point.

like image 162
Stephen C Avatar answered Sep 23 '22 17:09

Stephen C


Because that syntax simply isn't defined? Besides, x < y evaluates as a bool, so what does bool < int mean? It isn't really an overhead; besides, you could write a utility method if you really want - isBetween(10,x,20) - I wouldn't myself, but hey...

like image 44
Marc Gravell Avatar answered Sep 21 '22 17:09

Marc Gravell