【问题标题】:Converting string[][][] to string[][] in f#在 f# 中将 string[][][] 转换为 string[][]
【发布时间】:2014-08-15 16:22:18
【问题描述】:

我在使用 F# 时遇到了一些问题,因为我正在学习。我有类似下一个代码的东西:

let A = [| [| [|"1";"Albert"|];[|"2";"Ben"|] |];[| [|"1";"Albert"|];[|"3";"Carl"|] |] |]

(A类:string[][][]

我正在尝试将 A 转换为:

let B = [| [|"1"; "Albert" |] ; [| "2"; "Ben"|] ; [| "3"; "Carl"|] |]

(B型:string[][]

我不知道该怎么做。我一直在尝试一些for 和递归函数,但我不明白。

【问题讨论】:

    标签: sorting f# type-conversion


    【解决方案1】:

    您可以使用Array.concatstring[][][] 转换为string[][],然后使用Seq.distinct 删除重复的字符串数组。

    let b = 
        [| [| [|"1";"Albert"|];[|"2";"Ben"|] |];[| [|"1";"Albert"|];[|"3";"Carl"|] |] |]
            |> Array.concat
            |> Seq.distinct
            |> Seq.toArray
    

    【讨论】:

      【解决方案2】:

      这里有几个其他选项可以帮助您更好地概念化此类问题:

      let A = [| [| [|"1";"Albert"|];[|"2";"Ben"|] |];[| [|"1";"Albert"|];[|"3";"Carl"|] |] |]
      
      //Matthew's answer
      //This is exactly what you were asking for.  
      //It takes all the subarrays and combines them into one
      A |> Array.concat
        |> Seq.distinct
        |> Seq.toArray
      
      //This is the same thing except it combines it with a transformation step, 
      //although in your case, the transform isn't needed so the transform 
      //function is simply `id`
      A |> Seq.collect id
        |> Seq.distinct
        |> Seq.toArray
      
      //The same as the second one except using a comprehension.  
      //This form makes it somewhat more clear exactly what is happening (iterate 
      //the items in the array and yield each item).
      //The equivalent for the first one is `[|for a in A do yield! a|]`
      [for a in A do for b in a -> b] 
      |> Seq.distinct
      |> Seq.toArray
      

      【讨论】:

        猜你喜欢
        • 2021-09-28
        • 1970-01-01
        • 2021-07-04
        • 2020-06-10
        • 2019-09-10
        • 2021-12-21
        • 2021-07-25
        • 2011-02-02
        相关资源
        最近更新 更多