I wrote this F# function to partition a list up to a certain point and no further -- much like a cross between takeWhile
and partition
.
let partitionWhile c l =
let rec aux accl accr =
match accr with
| [] -> (accl, [])
| h::t ->
if c h then
aux (h::accl) t
else
(accl, accr)
aux [] l
The only problem is that the "taken" items are reversed:
> partitionWhile ((>=) 5) [1..10];;
val it : int list * int list = ([5; 4; 3; 2; 1], [6; 7; 8; 9; 10])
Other than resorting to calling rev
, is there a way this function could be written that would have the first list be in the correct order?
aux (fun acc l -> f (h::acc) l) t
and calling it asaux (fun a b -> (a,b)) l
, if that's allowed in F#. this would avoid the tuple unpacking and repacking on each continuation call, and might become faster overall (again, if the compiler doesn't already optimize this on its own). – Rollick