What's the best way to splice one list into the middle of another in F#?
For example, suppose the lists are [1; 2; 3; 4] and [7; 8; 9] respectively, and the splicing point is halfway along the first list, the result should be [1; 2; 7; 8; 9; 3; 4].
By 'best' I mean simplest/most idiomatic, on condition that it takes time no more than linear in the length of the result.
CodePudding user response:
I'd just use the built in List.insertManyAt - no need to invent anything.
CodePudding user response:
If you're already on F# 6, I would indeed follow Jackson's advice and just use the newly introduced List.insertManyAt.
If you're still on an older version and if you're fine with exceptions when the index is out of bounds, you could go with something like:
let spliceAt index newList spliceList =
let l1, l2 = List.splitAt index spliceList
l1 @ newList @ l2
Or if you want a total function:
let spliceAt index newList spliceList =
if List.length spliceList < index
then
None
else
let l1, l2 = List.splitAt index spliceList
Some (l1 @ newList @ l2)
