I need to split a string into parts of varying predefined lengths, given as a sequence of integers. After a first imperative attempt using a sequence expression and a reference cell, I have now come up with this implementation that uses Seq.scan
and doesn't need mutability:
let segmentString lengths (input : string) =
let folder (start, parts) lengthHere =
let partHere = input.Substring(start, lengthHere)
start + lengthHere, partHere :: parts
let results = lengths |> Seq.scan folder (0, [])
let _, resultParts = Seq.last results
List.rev resultParts
This works and is probably "good enough", but I wonder whether there are things that could be improved or more idiomatic (other than error handling and allowing more generic inputs than strings; I left those out because they are not a concern right now). What especially bugs me is the need to reverse the results list at the end, but obviously, I could only add the new part as the head of the aggregate list in the folder
function.
lengths
is smaller than the length ofinput
? Just ignore the rest of theinput
, like your code does? \$\endgroup\$