时间:2010-07-26 11:37:20

标签: f# puzzle cartesian-product

3 个答案:

答案 0 :(得分:10)

答案 1 :(得分:1)

这是一个解决方案'a list list -> Seq<'a list>来计算n个列表的笛卡尔乘积,并进行惰性求值。我把它写成了Python的itertools.product

的F#模拟
let product lists = 
    let folder list state =
         state |> Seq.allPairs list |> Seq.map List.Cons 
    Seq.singleton List.empty |> List.foldBack folder lists

它基于F {4.0中引入的List.allPairs

答案 2 :(得分:0)

这是第一次尝试列表版本。我认为它可以清理一下。

let rec cart nll = 
  let f0 n nll =
    match nll with
    | [] -> [[n]]
    | _ -> List.map (fun nl->n::nl) nll
  match nll with
  | [] -> []
  | h::t -> List.collect (fun n->f0 n (cart t)) h
相关问题