Robin Heggelund Hansen
Posted on August 10, 2018
I recently did some work which required me to create a sub-section of an Array
. This can be done by using Array.slice
but doing so always gives me the feeling that there is room for improvement.
To explain why, let's start by looking at a small example:
Array.slice 2 5 someArray
It isn't immediately obvious to me what this does. I know it creates a sub section, but when reading this I always have to stop up and calculate what the result will be. Usually, because I don't use this function too often, I also have to look up the documentation to check if the from and to indices are exclusive or inclusive.
The conclusion is that this particular code will create a new array, containing the values of indices 2, 3 and 4 of someArray
. This might not seem too bad when you actually want to extract a sub-section of an array from some index and to (but not including) another, but in my experience that is rarely the case.
Usually what you -- well, I -- want is either to remove the first couple of elements, or to remove the last couple of elements. Since slice
is all we got, we've always got to consider what value to use for both arguments, which adds a slight, but unnecessary, mental overhead.
For instance, removing the first two elements is implemented as:
Array.slice 2 (Array.length someArray) someArray
This doesn't read as easily as Array.drop 2 someArray
, but another problem is that it doesn't play well with pipelines. Removing the last element is easier as slice
supports negative indices, although it is a little more cryptic than it has to be:
Array.slice 0 -1 someArray
Even if you actually want a true sub-section, I'd argue that it would be easier to understand the code if you expressed it as two separate operations, like this:
someArray
|> Array.drop 2
|> Array.take 3
or
someArray
|> Array.drop 2
|> Array.dropLast 2
In summary, I believe slice
is a bad fit for functional programming. Using functions which have a clear intent and an intuitive usage is a better fit, and so I believe slice
should be replaced with take
, takeLast
, drop
and dropLast
.
Posted on August 10, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.