Oops. I just tried to define a function like this:...
# announcements
k
Oops. I just tried to define a function like this:
Copy code
fun isBetween(x, edge1, edge2): Boolean = x in (edge1 .. edge2)
but that doesn't Do What I Mean because
5 in (10 .. 1)
is false. Is there anything in the standard library that handles this already, or do I have to add an
if edge2 < edge1
in there to make sure they're the right way around?
d
(10..1)
doesn't work because the rangeTo operator only works for incremental ranges
a
works fine. You do get a warning though.
Another option:
Copy code
fun isBetween(x: Int, edge1: Int, edge2: Int): Boolean = x in (edge1..edge2) || x in (edge2..edge1)
g
Creating 2 ranges (or even one range as in original snippet) just to check range looks as overkill for me, why not just check which edge is bigger and just compare with x?
a
Yeah, someone suggested
x in (minOf(a, b)..maxOf(a, b))
I would side with readability, what would what you are suggesting look like, this?:
x >= minOf(a, b) && x <= maxOf(a, b)
g
Yes, no ranges needed
a
It's fine, lots of options. Depends if you like to optimize upfront and like code that looks like
c
.
🧌
g
Imo simple compare not only more efficient but also more readable
a
I disagree on that. And efficiency here should be the compilers problem.
x in (edge1..edge2)
should be no less efficient than
x >= edge1 && x <= edge2
. If it is less efficient, that's a compiler failure IMO.
I feel Kt wants us to use these more natural language constructs like
in
and if we can't without a cost, that's on Kt's compiler team.
You even get hints in the IDE to convert to range checks.
And I think the byte code looks OK with the range check. I don't think it's doing the evil you think it's doing.
g
I actually talking about one check, not 2 consequence range checks
a
You're just substituting a basic
||
, for two static method invocations. If you want to talk efficiency, I think this is a case of profiling over theorizing (which is almost always the case).
Point is, looking at the bytecode:
Creating 2 ranges (or even one range as in original snippet) just to check range looks as overkill for me
This statement is false. There is no "creation" going on. The compiler seems to handle it quite efficiently. The IDE will even recommend it.
g
No static method invocations, just common if
I don't want to say about any significant or even visible difference, it's just simple and at least same level of readability
a
I'm not sure what method you are advocating now. Can you make that clear?