range() iterator

Post your working scripts, libraries and tools.
iseahound
Posts: 1434
Joined: 13 Aug 2016, 21:04
Contact:

range() iterator

Post by iseahound » 21 Mar 2021, 04:17

Simple range function I made while messing around with enumerators.

Code: Select all

range(a, b:=unset, c:=unset) {
   IsSet(&b) ? '' : (b := a, a := 0)
   IsSet(&c) ? '' : (a < b ? c := 1 : c := -1)

   pos := a < b && c > 0
   neg := a > b && c < 0
   if !(pos || neg)
      throw Exception("Invalid range.")

   return (&n) => (
      n := a, a += c,
      (pos && n < b) OR (neg && n > b) 
   )
}
Similar to Python range().

Code: Select all

for n in range(5, 0, -1)
    if MsgBox(n, "Continue? #" A_Index, "y/n") = "No"
        break
       

User avatar
Delta Pythagorean
Posts: 627
Joined: 13 Feb 2017, 13:44
Location: Somewhere in the US
Contact:

Re: range() iterator

Post by Delta Pythagorean » 16 Aug 2021, 07:11

Doesn't seem to work now, is there a chance you could update it?

[AHK]......: v2.0.12 | 64-bit
[OS].......: Windows 11 | 23H2 (OS Build: 22621.3296)
[GITHUB]...: github.com/DelPyth
[PAYPAL]...: paypal.me/DelPyth
[DISCORD]..: tophatcat


swagfag
Posts: 6222
Joined: 11 Jan 2017, 17:59

Re: range() iterator

Post by swagfag » 16 Aug 2021, 07:59

Code: Select all

#Requires AutoHotkey v2.0-beta.1
range(a, b:=unset, c:=unset) {
   IsSet(b) ? '' : (b := a, a := 0)
   IsSet(c) ? '' : (a < b ? c := 1 : c := -1)

   pos := a < b && c > 0
   neg := a > b && c < 0
   if !(pos || neg)
      throw Error("Invalid range.")

   return (&n) => (
      n := a, a += c,
      (pos && n < b) OR (neg && n > b) 
   )
}

User avatar
Delta Pythagorean
Posts: 627
Joined: 13 Feb 2017, 13:44
Location: Somewhere in the US
Contact:

Re: range() iterator

Post by Delta Pythagorean » 16 Aug 2021, 11:21

@swagfag
Beat 'em to it I guess lol

[AHK]......: v2.0.12 | 64-bit
[OS].......: Windows 11 | 23H2 (OS Build: 22621.3296)
[GITHUB]...: github.com/DelPyth
[PAYPAL]...: paypal.me/DelPyth
[DISCORD]..: tophatcat


vmech
Posts: 352
Joined: 25 Aug 2019, 13:03

Re: range() iterator

Post by vmech » 20 Aug 2021, 23:18

May be

Code: Select all

(pos && n <= b) OR (neg && n >= b)
in line 13 ?
Please post your script code inside [code] ... [/code] block. Thank you.

swagfag
Posts: 6222
Joined: 11 Jan 2017, 17:59

Re: range() iterator

Post by swagfag » 21 Aug 2021, 06:07

why? that would make it unlike a python range

iseahound
Posts: 1434
Joined: 13 Aug 2016, 21:04
Contact:

Re: range() iterator

Post by iseahound » 23 Aug 2021, 23:09

For some background on why a half open half closed interval is used:
https://www.quora.com/Why-are-Python-ranges-half-open-exclusive-instead-of-closed-inclusive

I myself would prefer a closed range, i.e. [0,3] being 0,1,2,3 as opposed to [0,3) being 0,1,2. I found it better to use Pythons convention for consistency.

Post Reply

Return to “Scripts and Functions (v2)”