Title
k

keturn

12/08/2018, 10:13 PM
Oops. I just tried to define a function like this:
``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

Davio

12/09/2018, 5:56 AM
``(10..1)``
doesn't work because the rangeTo operator only works for incremental ranges
a

Alan Evans

12/09/2018, 1:20 PM
works fine. You do get a warning though.
Another option:
``fun isBetween(x: Int, edge1: Int, edge2: Int): Boolean = x in (edge1..edge2) || x in (edge2..edge1)``
g

gildor

12/09/2018, 2:27 PM
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

Alan Evans

12/09/2018, 2:35 PM
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

gildor

12/09/2018, 2:45 PM
Yes, no ranges needed
a

Alan Evans

12/09/2018, 2:50 PM
It's fine, lots of options. Depends if you like to optimize upfront and like code that looks like
``c``
.
:troll:
g

gildor

12/09/2018, 2:51 PM
Imo simple compare not only more efficient but also more readable
a

Alan Evans

12/09/2018, 2:54 PM
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

gildor

12/09/2018, 3:11 PM
I actually talking about one check, not 2 consequence range checks
a

Alan Evans

12/09/2018, 3:28 PM
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

gildor

12/09/2018, 4:41 PM
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

Alan Evans

12/09/2018, 6:35 PM
I'm not sure what method you are advocating now. Can you make that clear?