Re: Factor

Factor: the language, the theory, and the practice.

Calendar Ranges

Tuesday, May 9, 2023

#calendar

A post recently titled Python’s Missing Batteries: Essential Libraries You’re Missing Out On caught my eye. One of my favorite parts about Factor is the large standard library that we ship with. Looking at blogs like these sometimes helps me notice functionality that we are missing.

One of the provided examples from the timeutils module is the daterange word that provides an iterator between a start and stop date:

start_date = date(year=2023, month=4, day=9)
end_date = date(year=2023, month=4, day=30)

for day in timeutils.daterange(start_date, end_date, step=(0, 0, 2)):
    print(repr(day))
    # datetime.date(2023, 4, 9)
    # datetime.date(2023, 4, 11)
    # datetime.date(2023, 4, 13)
    # ...

I realize that although we have numeric ranges, the current support for numbers doesn’t allow extending them so that timestamp arithmetic is implicitly supported. Some future version of Factor might fix this when we finish merging support for multiple dispatch, but in the meantime I added a timestamp-range object that works identically to range but with calendar objects.

The above Python example would look something like this:

IN: scratchpad USE: calendar.ranges

IN: scratchpad 2023 4 9 <date-utc>
               2023 4 30 <date-utc>
               2 days <timestamp-range> [ . ] each
T{ timestamp { year 2023 } { month 4 } { day 9 } }
T{ timestamp { year 2023 } { month 4 } { day 11 } }
T{ timestamp { year 2023 } { month 4 } { day 13 } }
...

The current implementation has <timestamp-range> work the same way as <range> as it assumes an inclusive range [from,to]. Give it a try!