1
votes

Is there a native function that behaves like Haskell's range?

I found out that 2..1 returns a list [2, 1] in PureScript, unlike Haskell's [2..1] returning an empty list []. After Googling around, I found the behavior is written in the Differences from Haskell documentation, but it doesn't give a rationale behind.

In my opinion, this behavior is somewhat inconvenient/unintuitive since 0 .. (len - 1) doesn't give an empty list when len is zero, and this could possibly lead to cryptic bugs.

  1. Is there a way to obtain the expected array (i.e. range of length len incrementing from 0) without handling the length == 0 case every time?
  2. Also, why did PureScript decide to make range behave like that?

P.S. How I ran into this question: I wanted to write a getLocalStorageKeys function, which gets all keys from the local storage. My implementation gets the number of keys using the length function, creates a range from 0 to numKeys - 1, and then traverses it with the key function. However, the range didn't behave as I expected.

1

1 Answers

1
votes

How about just make it yourself?

indicies :: Int -> Array Int
indicies n = if n <= 0 then [] else 0..(n-1)

As far as "why", I can only speculate, and my speculation is that the idea was to avoid this kind of iffy logic for creating "reverse" ranges - which is something that does come up for me in Haskell once in a while.