I am looking for a way to create a sequence consisting of every nth element of another sequence, but don't seem to find a way to do that in an elegant way. I can of course hack something, but I wonder if there is a library function that I'm not seeing.
The sequence functions whose names end in -i seem to be quite good for the purpose of figuring out when an element is the nth one or (multiple of n)th one, but I can only see iteri
and mapi
, none of which really lends itself to the task.
Example:
let someseq = [1;2;3;4;5;6]
let partial = Seq.magicfunction 3 someseq
Then partial
should be [3;6]
. Is there anything like it out there?
Edit:
If I am not quite as ambitious and allow for the n
to be constant/known, then I've just found that the following should work:
let rec thirds lst =
match lst with
| _::_::x::t -> x::thirds t // corrected after Tomas' comment
| _ -> []
Would there be a way to write this shorter?
To get every nth element in a list, a solution is to do mylist[::n].
To get every Nth element of an array:Declare an empty array variable. Use a for loop to iterate the array every N elements. On each iteration, push the element to the new array. The final array will contain every Nth element of the original array.
The seq() method, extracts a subset of the original vector, based on the constraints, that is the start and end index, as well as the number of steps to increment during each iteration. It accesses the element at the index of the given vector based on these constraints, and then appends it to a sequence object.
Seq.choose
works nicely in these situations because it allows you do the filter
work within the mapi
lambda.
let everyNth n elements =
elements
|> Seq.mapi (fun i e -> if i % n = n - 1 then Some(e) else None)
|> Seq.choose id
Similar to here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With