29 ms·
Always use [closed, open) intervals
- bob1029 4y agoI was just watching YouTube series on arithmetic coding and I was wondering why the intervals were specified this way. Makes a lot more sense now. The "b - a" use case is quite prevalent there.
- enqk 4y agoI think this has to do with the nature of the metric underneath. Closed-open intervals are the way to go for integers. However they don’t seen to be a good fit for sampling from continuuous space
- moring 4y agoWhen you are working on a continuous space, what exactly is the difference in a program whether you use a closed-closed or half-open interval? The only case that comes to my mind where it makes a difference at all is when you take discrete values from the interval and happen to hit exactly the end of the interval. But then the difference comes from the "discrete" part again. As long as you work on the continuous space, everything you typically do (e.g. integral, average, ...) give the same result no matter whether the end is part of the interval. (You mentioned sampling, but I'd suggest that sampling by just taking values without lowpass filtering first is a bad idea anyway, and with a filter you are back to an integral which doesn't care about open/closed)
- trashtester 4y agoIt has to do with how cpus do floating point division. Here is an article that discusses this, along with workarounds: https://dl.acm.org/doi/10.1145/3503512 https://dl.acm.org/doi/10.1145/3503512 From the abstract: "Drawing a floating-point number uniformly at random from an interval [a, b) is usually performed by a location-scale transformation of some floating-point number drawn uniformly from [0, 1). Due to the weak properties of floating-point arithmetic, such a transformation cannot ensure respect of the bounds, uniformity or spatial equidistributivity."
- andreareina 4y ago*half-open intervals. There have been times I needed an (open, closed] interval. But there have also been times when I wanted a fully closed interval because I was setting an arbitrary limit and it's easier to tell a user "100 is the maximum" versus "it must be below 100”, so what value should be put to max out out, 99? 99.99? etc To add some nuance I'd say that if you're dividing a larger interval into smaller subintervals then a half-open one is probably what you want.
- eurasiantiger 4y agoThis is not universal advice. If it’s nonsensical for your app to have start-end events of zero length, nothing in the article applies, and using closed intervals does make things a bit cleaner.
- eigenspace 4y agoThere are convincing cases one can make in favour of half-open intervals (at least in certain circumstances), but this isn’t it. This is just a rambling, absolutist mess.
- cuteboy19 4y agoWhy not? The precision one sounds convincing and I don't have any obvious counters
- kreetx 4y agoLet's say you want to find accommodation from day x to y, would you rather have [x, y + 1) as the interval in the code? In other words, I think the blog post lists problems the author has had and in those cases an open-closed interval would have worked better. But one could come up with an opposite case, would that be equally true?
- zasdffaa 4y agoIIRC (bit rusty now) python makes you do exactly [x, y + 1) in code and it pisses me off which is why I did my own trivial end-is-included range for loops.
- bigDinosaur 4y agoOtherwise would result in surprises like range(10) giving 11 values, violating convention. I admit I usually have to pause to remember whether it's inclusive of the upper bound or not.
- asplake 4y agoOf course if datetimes are involved, you need to go up midnight. So you’re back to +1 and a half-open range
- rieTohgh6 4y agoI am more surprised it is about numbers. I found it more important to take care when dealing with date ranges in databases. And SQL "BETWEEN" lures you into using [from, to], which is great way to shoot yourself in foot. So just my 2 cents: - what are you going to do when you need to split [a,b] into multiple parts, for performance reasons? [a,c], (c,b] ? Can your codebase handle different interval types? Having [a,b) everywhere is simpler - stuff like 23:59:59.999999999 is code smell, well until database rounds it up, to next day, then it turns into bug
- the_cramer 4y agoThis depends on use case. If you are doing a frontend layer on top of closed-open, then the frontend will have to handle the points the article is rambling about. Users are used to selecting a daterange in closed closed format for example.
- pcthrowaway 4y agoIt depends on the use-case. Selecting an airbnb booking for example, you pay by the night, and the last day is check-out day, so it's sort of [bookingStart, bookingEnd). Though from a user perspective, they are still there on the final day. Still, I think there's some nuance to this, as it's generally understood the date range they select isn't the number of nights they expect to pay for.
- knorl 4y agoI think this advice could be better summed up into: to minimise off-by-one errors, choose a consistent strategy for describing intervals, and stick with it as much as is sensible.
- erik_seaberg 4y ago[closed, open) isn’t the only strategy that works, but it should be preferred because it’s so common.
- BiteCode_dev 4y agoIt's the default in Python, and it's more helpful that not, so I would say it's a good design decision. But "always" is a dangerous word in engineering, and in this case, definitly not warranted. Case in point, last week I worked with list ofdates, and I needed the last date to bracket my sliding windows as a time period cleanly.
- bheadmaster 4y agoI prefer [a, b) intervals because they encode two pieces of important information directly: 1. The first element (a) 2. The length (b-a) Which are what we most often need.
- eurasiantiger 4y agoIf, however, a and b are dates, these operations are nonsensical, as is using anything else except closed intervals: for date range comparisons it is much more understandable to use start-of-day on a and end-of-day on b.
- bheadmaster 4y ago> If, however, a and b are dates, these operations are nonsensical If you encode dates as number of days since some fixed date, they can be seen as numbers on a timeline, so the start date and the length (in days) of a "date interval" could be useful information. If you mean that subtracting two dates represented as strings of "YYYY-MM-DD" form is nonsensical... well, duh. > for date range comparisons it is much more understandable to use start-of-day on a and end-of-day on b I personally agree with this, but then again, "more understandable" is a subjective notion. I don't see how it make open intervals for dates nonsensical in itself. "You're arriving on 15th and going home 23rd" implies that you're there 23-15=8 full days (unless we count the arrival/departure half-days as full days, in which case the arithmetic itself breaks down, so it doesn't matter which intervals we use mathematically) - that's an open interval.
- eurasiantiger 4y agoEncoding dates in data in any other way than native date datatypes or full ISO date/timestamp strings is incredibly dangerous and prone to tz and dst conversion issues. It still might fit some niche use though. I was thinking more in line with some sort of Date entities. Your example, as you point out, is flawed with respect to reality: no system would record arrival/departute dates and expect to calculate accurate length of stay, except in full days, as in b-a-1 = 7 days, effectively making the example use a closed interval if it were implemented in reality. Imagine a hotel reservation system using just dates. Arrival on the 15th and departure on the 23rd would mean a reservation from the 15th to the 22nd, while the 23rd would already be free for someone else to book.
- sshine 4y agoThis is one of those "well, of course!" pieces. But I've bookmarked it, in case I run into someone who thinks they disagree, in which case I can offload the explanation. I had a similar incident with colleagues who had discovered the "Default" trait and starting adding defaults to everything, including things that didn't have good defaults, and things where they didn't mean default but actually something quite specific such as "empty". The canonical "don't do that!" blog post didn't exist, so I had to create one.
- Rygian 4y agoSo, if I want to book the night from Jan 13th to Jan 14th on AirBNB (which is the very first example given in the post), I should search for "Arrival Jan13th, Departure Jan 13th"? As with any piece of advice, there are cases where it applies and cases where it does not apply. Or, in other words, someone can claim "Well, of course!" for the opposite advice.
- deleted 4y ago[deleted]
- sshine 4y agoNo, a [closed, open) interval of [Jan 13, Jan 13) would give you 0 nights. A [closed, open) interval of calendar dates incidentally does correspond to the number of nights spent. So booking [Jan 13, Jan 14) would mean spending one night. The hotel gives you until, say, 11:00 to get out the next day without paying for that date. Half-open intervals are neat because they concatenate without overlap. So [Jan 13, Jan 14) + [Jan 14, Jan 15) = [Jan 13, Jan 15). This is a very convenient property when dealing with dates in particular, but also indices over arrays.
- Rygian 4y agoSo it boils down to what is being represented: an amount of items versus an amount of _boundaries_ across items. When I'm booking that stay between Jan 13th and Jan 14th, and I am presented with options, the ones that say "sleeps 2" does not mean [1, 2) but rather [1, 2] and the one that says "sleeps 6" does not mean [1, 6) but rather [1, 6].
- ChrisMarshallNY 4y ago> Never, ever, ever use [closed, closed] intervals I’m not really a fan of “never,” or “always” rules, when it comes to programming. I’ve found it’s usually better to have a “make sure to justify deviations from” heuristics. I usually use [closed..open) ranges (as they are called in Swift), but sometimes, an inclusive range is a lot more appropriate, for expressing an operation (for example, I may express a range as start...end, as opposed to start..<(end + 1)).
- Tuna-Fish 4y ago> as opposed to start..<(end + 1) This is not just a convenience thing. ..(end+1) is dangerous, if end is the largest representable number.
- teddyh 4y agostart..<inf
- mananaysiempre 4y agoSee also “My least favourite Rust type”[1] for an argument that Rust’s (polymorphic) range type should have used inclusive bounds. [1] https://ridiculousfish.com/blog/posts/least-favorite-rust-type.html https://ridiculousfish.com/blog/posts/least-favorite-rust-ty..., discussed two years ago in https://news.ycombinator.com/item?id=24546928 https://news.ycombinator.com/item?id=24546928
- vasergen 4y agoAgree, in programing you can always find a contrargument to any "never ever use X". I noticed that people often treat such phrases godmatically and then use it in another context, where it might not be true. I like more phrasing it like this "in 90 % of the cases it is better to use X over Y", to leave the room for other options. But it is not a catchy phrase if you want to write a blog post. Nevertheless I really like the points the author gave, something I didn't thought about before.
- inanutshellus 4y agoI've moved away from this. Advice is supposed to convey information simply and efficiently, and "asterisks" for every edge case just muddle it. Now my pet peeve has moved to folk wheedling about 100% accuracy in advice. ;-) e.g. Great advice: "Never run a red light" vs Technically-correct-but-will-never-be-read advice: "Don't run a red light, unless you're on a bicycle and you know that the intersesction you're at is on a weighted sensor that you're not going to set off. In which case, check your local laws on how to get through the intersection. Also, this likely applies to motorcycles. But not all motorcycles, so check your motorcycle's weight and cross-reference it to the weight sensors in your intersection (you'll need to contact your municipal engineering corps to get this). Also, one should look up for falling pianos at this point as well, just in case, because I can't say the word 'never'."
- zx8080 4y agoAm I the only one who noticed a bit unusual (or not?) ligature for 'st'?
- Semaphor 4y agoYou might have to provide a screenshot, because I don’t have one (Firefox, Win)
- jwilk 4y agohttps://i.imgur.com/hTbvwR9.png https://i.imgur.com/hTbvwR9.png
- elcaro 4y agoDiscussion of the ligature issue (and a screenshot) in the Reddit post comments. https://old.reddit.com/r/programming/comments/z18gb6/comment/ixa2q6w https://old.reddit.com/r/programming/comments/z18gb6/comment...
- pwg 4y agoYes, terribly ugly ligature. You can turn it off by using dev tools to remove the '"dlig" 1' entry in the "font-feature-settings:" CSS attached to the body element.
- zasdffaa 4y agoI know Dijkstra's paper and it's short, good and should be read but this article is wrong in saying always. It feels like a newbie programmer came across a good thing then lost all proportion; use the right tool for the right job, as ever.
- personalityson 4y agoFuck Dijkstra, his only argument was "this is ugly"
- zasdffaa 4y agoIt's a short paper so read it. He justifies it then backs it up with experience from Mesa.
- pwdisswordfish9 4y agoThanks, I have always been using the wrong tool for the job. Now I understand why I should stop.
- elcaro 4y agoI'll repeat the sentiment that "always" and "never" rules usually have their fair share of exception. And while I agree that [closed, open) intervals are often the best choice... sometimes what you want is [closed, closed], or (open, open), and it's nice to use a language that makes that easy. For example, Raku makes it easy to do: [closed, closed] with ($a .. $b) [closed, open) with ($a ..^ $b) (open, open) with ($a ^..^ $b) (open, closed] with ($a ^.. $b)
- rav 4y agoHalf-open intervals are why I try as much as possible to stay away from languages that use 1-based indexing (Lua, Julia, Matlab, R, ...) - 1-based indexing lends itself to closed intervals because an array of N elements has [1,N] as its index range, whereas 0-based indexing lends itself to half-open intervals because an array of N elements has [0,N) as its index range. ------- However, I know of one case where closed intervals really shine. Consider displaying a zoomable map in tiles. On a given zoom level, each tile has some coordinates (x;y) where x and y are integers denoting the virtual column and row. Suppose that we allow zooming out by a factor 2, so that two-by-two tiles are aggregated into a single tile. Then a natural choice for the coordinates of the zoomed-out tile are (floor(x/2);floor(y/2)), that is, divide by two and round down. Suppose that a dataset has data on tile coordinates [x1,x2]×[y1,y2], meaning that there's only data on tiles (x;y) where x1≤x≤x2 and y1≤y≤y2. These are closed intervals, but stay with me - the reason they are nice in this case is because of how you compute the range of valid tile coordinates when you zoom out: The range becomes [floor(x1/2),floor(x2/2)]×[floor(y1/2),floor(y2/2)] - that is, you simply divide the range endpoints by two and round down. If you try to do this with half-open intervals, then you need some +1/-1 shenanigans, which are normally what I try to avoid by going for half-open intervals.
- Steltek 4y agoI wonder if a lot of Lua's 1-indexed pain would be avoided by encouraging for-each style loops. Unless you need a specific sub range within an array, for-each will get you pretty far.
- carpenecopinum 4y agoThat's a big thing with Julia actually. A lot of people first getting into it criticise it for its use of 1-based indexing (I'm not the biggest fan of it either tbh), but in reality, there are very few cases in which you actually directly interact with array indices at all. And even if you do, the idiomatic way to iterate over the indices of an array is to use the `indices`-function, which has the benefit of working with multidimensional arrays, or arrays that start with an index other than 1.
- 4y ago
- Gehinnn 4y agoDon't call you integer bound vars `start` and `end` please. Either use `start` and `endExclusive` or start and length - this greatly reduces confusion. In my experience, half opened integer intervals lead to fewer `- 1` in the code.
- lupire 4y agoGood luck with the C++/STL standards committee.
- Etherlord87 4y agohow about `start` and `stop`?
- branko_d 4y agoI prefer `pastEnd`, perhaps in reaction to the original SGI STL, where the documentation called it "past end", but the actual names in the code were just `end`. For example, look at the... https://www.boost.org/sgi/stl/stl_introduction.html https://www.boost.org/sgi/stl/stl_introduction.html ...where the documentation is very careful to say "one past the end of the range", and then they proceed to just call `v.end()`. I always thought that was silly.
- zestyping 4y agoI always use "start" and "stop" for half-open intervals. For closed intervals, I use "start" and "end" or "first" and "last". The terminology is significant!
- chenglou 4y agoQuite a few APIs use a pair of `{start, length}` instead, which in the context of the post's example, is even clearer. Empty interval would be `length == 0`, time interval would be a single array of `starts`, etc. Fewer subtractions (to get length) usually end up nicer too.
- jmull 4y agoHalf-closed is generally good because it tends to reduce off-by-one errors. But this article overstates the case. Especially for floating-point, where the distinction between a < b and a <= b is not straightforward. Some times you’re modeling closed intervals, and in that case using closed intervals is the right decision. The “splitting by time” section should probably just be removed, since it confuses the point and doesn’t add anything. The scenario doesn’t really make sense (if you wanted this you’d store the registration time and get the hour you’d be better off by truncating the value, not using an interval). Also, if you’re going to be doing math on time values, you better know the precision of the values you’re working with (among many other things). Intervals, however closed or open aren’t going to help you there. Maybe I shouldn’t criticize so much, since I agree with the general point. But this makes the case awkwardly.
- _xnmw 4y agoWhy would you want a half-open interval when booking an AirBnB or flight? If I search for flights from February 24 to February 24 I don’t expect the empty interval.
- q-big 4y ago> If I search for flights from February 24 to February 24 I don’t expect the empty interval. The expectation depends on how you define "from" and "to" :-D Since the HN community is quite mathematically-minded, I'd expect there all four possible kinds of definitions in the inner minds of HN members. :-D
- twiss 4y agoAirBnB bookings are actually half-open, because you book a number of nights - so if you book December 1 - 3, you book the nights of December 1 and 2 - excluding 3. This seems expected to me. However, as an AirBnB host, this bit me once because if you set that you're available on December 1, 2 and 3, guests can actually book December 1 - 4. But this is more because availability uses individual dates (almost like closed ranges) instead of half-open ranges like bookings do. For booking flights, though, it's more like you're booking two individual flights on specific dates, it's not really a range at all, and so it doesn't really matter whether you think of it as open or closed. The flight search engine might want to check that the second flight departs after the first flight lands, but that has more to do with the flight times than the dates you enter.
- kangalioo 4y agoFlights are just a set of two dates, not a range, like the other comment mentions. I thought about it and this applies to an AirBnB, or more generally, a vacations, too. A vacation from Nov 25 to Nov 27 doesn't mean you stay from Nov 25 0:00 to Nov 27 23:59:59, but it means "arrive sometime Nov 25, leave sometime Nov 27" - a set of two dates
- Linosaurus 4y agoYeah, when talking to humans about dates, [closed, closed] is useful. Once you swap to a higher precision format for an actual database search, you get all the messiness from the article.
- deleted 4y ago[deleted]
- phoe-krk 4y agoHow does [2, 2) make sense?
- layer8 4y agoIt’s the empty interval. It’s the set of numbers x for which x >= 2 and x < 2, which is none, and hence the empty set. It’s the equivalent of this for loop (for integers): for (int i = 2; i < 2; ++i) { … } The body of the loop will be executed zero times.
- chkas 4y agoPython uses "closed open" intervals with `range(0, n)`, the reverse is then `range(n - 1, -1, -1)`, which is then highly unintuitive. This in connection with 0-based array indexing makes certain algorithms then very cumbersome. For example Knuth-Shuffle. In Python this is: from random import randrange x = [10, 20, 30, 40, 50 ] for i in range(len(x) - 1, 0, -1): r = randrange(i + 1) x[i], x[r] = x[r], x[i] print(x) With 1-based indexing and inclusive ranges it would be much more understandable: a[] = [ 10 20 30 40 50 ] for i = len a[] downto 2 r = random i swap a[i] a[r] end print a[]
- mananaysiempre 4y agoIn Python, reversed(range(0, n)) (which is also a thing you can write—does that help?) is indeed written range(n-1, -1, -1), but I think I recently encountered a language where that was written as (the local syntax’s equivalent of) range(n, 0, -1), that is to say the rule was not “start inclusive, end exclusive” but “low inclusive, high exclusive”. I’m not sure what language it was and whether this option ultimately ends up more intuitive, but in any case it’s a valid option. (One difference is that the start-end rule can work polymorphically with equality only, while the low-high rule requires an ordering.)
- chkas 4y agoWith Knuth-Shuffle, it would be: for i in reversed(range(1, len(x))): That makes it better, but not much.
- formerly_proven 4y agoA potential issue with reversed(range(...)) is reversed() eagerly constructing the entire range.
- mananaysiempre 4y agoNope: unlike, say, sorted(), reversed() will never force an iterator into a sequence—it will either call __reversed__ or fall back to __len__ and __getitem__. An iterator needs to know how to reverse itself, or it’s out of luck. (Which is quite annoying because it forces you to write a class rather than a generator function.) Ranges are in the former category, they know how to reverse themselves[1]. (Yet for some reason range(0, 42) and range(41, -1, -1) repr themselves as range(0, 42) and range(41, -1, -1) respectively while reversed(range(0, 42)) is instead <range_iterator object at ...>. Truly, I cannot touch anything without finding a bug or at least a suspiciously insectoid lifeform.) [1] https://github.com/python/cpython/blob/7e3f09cad9b783d8968aa79ff6a8ee57beb8b83e/Objects/rangeobject.c#L1115 https://github.com/python/cpython/blob/7e3f09cad9b783d8968aa...
- ur-whale 4y agoWholeheartedly agree that sticking - where possible - to [closed, open) is a good idea. It has helped me tremendously when implementing, e.g. computational geometry algorithm. Robust triangle rasterization comes to mind. Another interesting point: in the weird corner of the world where I grew up, half-open intervals were always denoted : [low_bound, hi_bound[ I am of course completely biased, but I've always found this notation much more elegant and intuitively obvious than the [low_bound, hi_bound) that seems to be the prevalent norm in the anglo world. Using '[' after the upper bound clearly shows that we're open at the top whereas the ')' is fairly arbitrary. And while I'm on the topic of weird culture-induced quasi-arbitrary biases: I had a math teacher that would bark (and I mean BARK!) at us if we ever used '>' in inequalities. The justification was that with this constraint, all inequalities ended up written and laid out with its two members respecting the standard "left-to-right" drawing of the real line, which made it much easier to picture what was going on geometrically. It also enforced consistency throughout a long demonstration - one less thing added to the cognitive load. He was made fun of a lot by the student body, of course, but later in life, as a programmer, I have found myself sticking to the habit and I always force myself to mostly use '<', very rarely '<=, and almost never '>' and ">". I find this makes code much more readable, just like back in the days of my old teacher with math inequalities., and pretty much for the exact same reasons. Of course, doing that does not help at all when reading other folks code, those uncivilized heretical users of the 'greater than' form.
- vglocus 4y agoI have recently been on the other side of this argument for specific case. In our case we (users of our API) are to specify date ranges, representing a list of partitions. So we are not counting nights between dates, but rather a set of daily or hourly buckets. Here (maybe even only here) I argue that inclusive ranges feel more intuitive. I find it much more intuitive to represent the 1st 7 days of January as ['2022-01-01', '2022-01-07'] compared to ['2022-01-01', '2022-01-08'). Another very common example is to specify the last 7 days (incl 'today') in which case I find [today().minusDays(6), today()] to be a clearer representation than ['today().minusDays(6)', 'today().plusDays(1)')
- bentcorner 4y agoYour 1st 7 days still works with an open interval: ['2022-01-01', '2022-01-01' + days(7) ) Also, isn't this 6 days? [today().minusDays(6), today()] --> ['2022-11-16', '2022-11-22'] To be fair, I'm considering these dates/times as singular points in time to the smallest resolution available in whatever time system is being used.
- dragontamer 4y agoEhh, this post misses the important tidbid. You should keep your code consistent across your organization, so that a large number of programmers knows how your code works. You should have a "default writing style", and the "default writing style" should be used unless you have very, very, very good reasons to avoid it. (And an errant +1 or -1 here and there isn't a good enough reason to switch). There are four styles of intervals. Lets say you want to represent a loop of 5 iterations numbered [555, 556, 557, 558, 559]. You've got: * [closed, closed] -- [555, 559] * [closed, open> -- [555, 560> * <open, closed] -- <554, 559] * <open, open> -- <554, 560> There's not much difference to any of these four. As long as you pick a singular choice, get comfortable with its quirks, and make it consistent across your organization, you get benefits. The main reason we do [closed, open> is because Dijkstra (father of structured programming back in the 1960s), argued to use [closed, open>, when presented with all these options. (and argued for zero-indexed as well). The "[closed, closed]" set is one-too-small (559 - 555 == 4), so you need to add +1 to the representation. The <open, open> set is one-too-large: (560 - 554) == 6. So this too seems prone to off by one error. [closed, open> and <open, closed] are both the correct size of 5 when you subtract, but both "includes" a number that doesn't exist. In [closed, open>, the latter number isn't part of the array (560 is "one past the end), while in <open, closed>, the first number isn't part of the array. Make that what you will of it. [closed, open> became a programmer convention because of these reasons. The important bit is to know all the quirks / off by one errors associated with this representation.
- weavejester 4y agoOnce you go beyond integers, using [closed, open) or (open, closed] becomes more important, because otherwise you cannot represent adjacent intervals.
- HelloNurse 4y agoThe empty interval problem applies to integers too: [15,15) and (15,15] are empty, [x,y] is not for any x and y.
- 4y ago
- branko_d 4y agoJust for completeness I'll mention that there is another style: start, count This seems to be popular in .NET ecosystem.
- mjmsmith 4y agoNSRange is defined the same way in the (macOS) Foundation framework.
- bouke 4y agoThat’s for creating an enumerable of discrete integers, not for defining an interval.
- branko_d 4y agoIf by "enumerable of discrete integers" you meant Enumerable.Range, it's not just that. Other examples include String.Substring, Array.Fill, Stream.Read, Span constructor etc. If you meant it's not practical for non-integer types such as floats or dates, then of course you are right.
- tmtvl 4y agoI'd say bound, range is an acceptable way of defining an interval, it can save space for multidimensional intervals, though at the cost of increased computation.
- personalityson 4y agoClosed/open makes sense for continuous measures, for integers closed/closed is more readable
- deleted 4y ago[deleted]
- lupire 4y agoOnly for integer ranges that are not concatenated.
- hans_castorp 4y agoFWIW, Postgres converts all ranges (=interval in this context) for discrete data types to half open intervals even when a closed one was requested. So the daterange '[2022-01-01, 2022-01-07]' will result in [2022-01-01,2022-01-08) and the integer range '[1,7]' will result in '[1,8)' So it seems the Postgres devs agree with the author. Edit: typo fixed for integer range
- zmgsabst 4y agoSmall comment: I think you have your integer example backwards, ie [1,8) = [1,7].
- hans_castorp 4y agoYes, of course ;) Copy & Paste error.
- return_to_monke 4y agoI am surprised I can't see this here. Wasn't anyone else taught [closed; closed] and ]open; open[ notation in school?
- aftbit 4y agoNope, I learned [closed, open) in school and .. vs ... in ruby. Python range() is [closed, open) so that's what I use everywhere now.
- lkuty 4y agoYes I did. In Belgium in the 80's and 90's. But on Internet, I mostly see [a,b) instead of [a,b[
- Pathogen-David 4y agoI'm from the US and I was taught the way it is in the article title. Can't say I've ever seen that before. It's an interesting notation, but I feel like if I encountered it out in the wild I might assume it was a typo if it was only on one side. (IE: If I saw `[100, 200[` I would think they meant `[100, 200]`)
- Leherenn 4y agoBoth forms are valid according to ISO 31-11. Your form is often called the "French notation" and I assume used more commonly in France and countries with French influences.
- danans 4y agoWhat's with the funny connected "st" in the article? I've never seen that before.
- Etherlord87 4y agoI don't see it, perhaps a different font loaded for me, but maybe you mean a ligature? https://en.wikipedia.org/wiki/Ligature_(writing) https://en.wikipedia.org/wiki/Ligature_(writing)
- danans 4y agoYes, that's it. I've not seen a ligature used that way in text before. English has words that can be spelled with ligatures to this day, but not for the sound "st" https://en.wikipedia.org/wiki/List_of_English_words_that_may_be_spelled_with_a_ligature https://en.wikipedia.org/wiki/List_of_English_words_that_may...
- dragonwriter 4y agoIts just a fancy typographic ligature, not a spelling “ligature” (which, in turn, is more of a letter with an optional decomposition as an anti-ligature) like ash (æ) or ethel (œ).
- nequo 4y agoAs it goes with maxims like this, it depends on the problem domain. In probability theory and statistics, a cumulative distribution function is defined as F(x) := Pr(X <= x), not Pr(X < x). Like others are saying, it is consistency within the code base that probably matters the most.
- lupire 4y agoThat difference only matters for discrete probability, and has the problem that the empty interval X<0 is impossible to represent.
- runarberg 4y agoThe notation here really bothered me. The author defines the [closed, open) interval [a, b) as the list of all numbers number x that fulfill a ≤ x < b. Good so far, but when they talk about the empty interval [a, a) we get into problem because a ≤ x < a is a nonsensical statement. a cannot be equal to and strictly less then it self. I think this is a problem when borrowing math concepts to programming. What the author is really talking about here is slicing, not intervals, and the slicing behavior is hopefully well defined on the construct you are working with, most of the time in a manner that makes sense to each construct, or in a consistent manner to other related constructs in the language. If the author would stick with programming concepts, I don’t think this is a rule we should abide to, rather, a guideline which can be employed. And I think most programmers value consistency, so this really isn’t that much of an issue.
- deleted 4y ago[deleted]
- nayuki 4y ago"[a, a)" and "a ≤ x < a" are actually shorthand for {x∈ℝ | a ≤ x < a}, which is the empty set ∅. This makes perfect sense.
- pwdisswordfish9 4y agoIt's not a nonsensical statement, just a necessarily false one. "2 + fish = chair" is a nonsensical statement.
- green-in-gold 4y agoThe other nice property of [closed, open) intervals is that they concatenate perfectly: [a, b) ++ [b, c) == [a, c)
- parekhnish 4y agoEven [closed, closed] intervals have that property: [a, b] + [b, c] == [a, c]
- cristoperb 4y agob would be included twice in that case, wouldn't it?
- jissa 4y agoRight, I think the hotel room use case helps a lot with the intuitions here. And it helps to see the COUNTER EXAMPLE: * Hotel A [Jan 10, Jan 13] means 4 nights; same as [Jan 10, Jan 14). * Hotel B [Jan 13, Jan 15] means 3 nights; same as [Jan 13, Jan 16). These intervals overlap! That is, if I try to get them together I book Jan 13 on both Hotel A and Hotel B. With the half-open interval is really easy to spot: you cannot concatenate unless the open-end and the closed-begin are the same. So you can concat [Jan 10, Jan 14) with [Jan 14, Jan 16); BUT you have an overlap if you see this [Jan 10, Jan 14) with [Jan 13, Jan 16) as in the previous examples. With the closed interval this is hard to see. As in the example by @parekhnish; it seems that [Jan 10, Jan 13] and [Jan 13, Jan 15] are concatenable and there's no overlap. But the final operation ends up booking on Jan 13 twice.
- jissa 4y agoNot to mention the sweetness of saying: * Jan 14 - Jan 10 = 4 nights * Jan 16 - Jan 13 = 3 nights I actually had to edit my previous comment, because I said [Jan 10, Jan 13] was 3 nights INSTEAD of 4 nights. I caught the error when I saw the [Jan 10, Jan 14) interval :-)
- green-in-gold 4y ago
- jwilk 4y ago> You could try [T, T-1], but that's a bit clunky and it won't work if T is a decimal number. Huh? What do they mean by "decimal number"?
- deleted 4y ago[deleted]
- layer8 4y agoThey mean a decimal data type: https://en.wikipedia.org/wiki/Decimal_data_type https://en.wikipedia.org/wiki/Decimal_data_type
- alexchantavy 4y agoDumb question but why is ‘[‘ called ‘closed’ and ‘)’ called ‘open’? I somehow would have thought the reverse.
- layer8 4y agoAn open interval doesn’t include its boundaries. It’s like a room missing one or more walls, and which hence is “open” towards the respective side(s). Imagine a series of adjacent boxes with shared walls, that you cut up. Depending on how you cut them up, each wall will stay with one of the boxes, which thus will remain “closed” on that side, while the other box who shared the same wall is now open on the side where you separated the boxes. +———+———+ | | | +———+———+ | V +———+ ———+ | | | +———+ ———+ closed open [0,1] (1,2]
- yjk 4y agoI assume the origins of how it's called ties to the mathematical definition of open/closed sets (https://en.wikipedia.org/wiki/Open_set https://en.wikipedia.org/wiki/Open_set). In an (imprecise) way, the closed set is a water balloon and the open set doesn't have the rubber balloon wrapping the water - I would consider the water balloon to be 'closed' in this case.
- nvartolomei 4y agoE. W. Dijkstra constructed a similar argument to argue that numbering should start at 0 https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/E...