Projecting a list of lists efficiently in F#

后端 未结 5 629
太阳男子
太阳男子 2020-12-03 08:47

I have to do projection of a list of lists which returns all combinations with each element from each list. For example:

projection([[1]; [2; 3]]) = [[1; 2]         


        
5条回答
  •  旧巷少年郎
    2020-12-03 09:06

    Here's a tail-recursive version. It's not as fast as some of the other solutions (only 25% faster than your original function), but memory usage is constant, so it works for extremely large result sets.

    let cartesian l = 
      let rec aux f = function
        | [] -> f (Seq.singleton [])
        | h::t -> aux (fun acc -> f (Seq.collect (fun x -> (Seq.map (fun y -> y::x) h)) acc)) t
      aux id l
    

提交回复
热议问题