我遇到了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
和递归函数,但我没有得到它。
答案 0 :(得分:5)
您可以使用Array.concat
将string[][][]
转换为string[][]
,然后使用Seq.distinct
删除重复的字符串数组。
let b =
[| [| [|"1";"Albert"|];[|"2";"Ben"|] |];[| [|"1";"Albert"|];[|"3";"Carl"|] |] |]
|> Array.concat
|> Seq.distinct
|> Seq.toArray
答案 1 :(得分:4)
以下是实现此功能的其他几个选项,可帮助您更好地概念化此类问题:
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