代码之家  ›  专栏  ›  技术社区  ›  SharePoint Newbie

如何调用Enumerable。从f_加入?

  •  5
  • SharePoint Newbie  · 技术社区  · 14 年前

    我有两个(元组的)序列,需要在上面进行连接:

    • 顺序1:【CITY1*PIN1】(CITY2*PIN2),(CITY1*PIN3),(CITY1*PIN4)]
    • 顺序2:【PIN1*ProductA】(PIN2*ProductB),(PIN1*ProductC),(PIN2*ProductA)]

    进入(元组的)序列:

    • [(city1*产品a),(city2*产品b),(city*产品c),(city2*产品a)…]

    在C中,我可以使用linq join扩展方法来实现这一点,比如:

    seq1.Join(seq2, t => t.Item2, t=> t.Item1,
        (t,u) => Tuple.Create(t.Item1, u.Item2))
    

    我该如何在f中完成这项工作?我在那里找不到join。

    3 回复  |  直到 14 年前
        1
  •  6
  •   Community CDub    8 年前

    > open System.Linq;;
    > let ans = seq1.Join(seq2, (fun t -> snd t), (fun t -> fst t), (fun t u -> (fst t, snd u)));;
    

    Seq at the docs at this question Seq.map2

    > let mapped = Seq.map2 (fun a b -> (fst a, snd b)) seq1 seq2;;
    
    val it : seq<string * string> =
      seq [("city1", "product1"); ("city2", "product2")]
    

    seq1 seq2

        2
  •  3
  •   Artem Koshelev    14 年前

    > let seq1 = seq [("city1", "pin1"); ("city2", "pin2")];;
    
    val seq1 : seq<string * string> = [("city1", "pin1"); ("city2", "pin2")]
    
    > let seq2 = seq [("pin1", "product1"); ("pin2", "product2")];;
    
    val seq2 : seq<string * string> = [("pin1", "product1"); ("pin2", "product2")]
    
    > Seq.zip seq1 seq2;;
    val it : seq<(string * string) * (string * string)> =
      seq
        [(("city1", "pin1"), ("pin1", "product1"));
         (("city2", "pin2"), ("pin2", "product2"))]
    > Seq.zip seq1 seq2 |> Seq.map (fun (x,y) -> (fst x, snd y));;
    val it : seq<string * string> =
      seq [("city1", "product1"); ("city2", "product2")]
    

    open System.Linq

    open System
    
    let seq1 = seq [("city1", "pin1"); ("city2", "pin2"); ("city1", "pin3"); ("city1", "pin4")]
    let seq2 = seq [("pin1", "product1"); ("pin2", "product2"); ("pin1", "product3"); ("pin2", "product1")]
    
    let joinSeq = seq { for x in seq1 do
                            for y in seq2 do
                                let city, pin = x
                                let pin1, product = y
                                if pin = pin1 then
                                    yield(city, product) }
    for(x,y)in joinSeq do
        printfn "%s: %s" x y
    
    Console.ReadKey() |> ignore
    
        3
  •  3
  •   Tomas Petricek    14 年前

    • List.zip List.map2

      Join Zip

    • seq { for city, pin1 in seq1 do 
              for pin2, product in seq2 do 
                if pin1 = pin2 then yield city, product }
      

      seq2 seq1 O(seq1.Length * seq2.Length)

      open System.Linq
      module Seq = 
        let join (seq1:seq<_>) seq2 k1 k2 =
          seq1.Join(seq2, (fun t -> k1 t), (fun t -> k2 t), (fun t u -> t, u)) 
      

      (seq1, seq2) 
         ||> Seq.join snd fst 
         |> Seq.map (fun (t, u) -> fst t, snd u)
      

    zip join