首页 > 解决方案 > F# 三个数组 - 用新值替换原始数组中的唯一值

问题描述

我有三个数组 - 第一个、第二个和第三个。second 包含 first 和 third 的唯一值,包含通过映射到 second 来替换 first 中的新值,如下所示:

module SOQN = 

   open System

   let first  = [|"A"; "B"; "C"; "A"; "B"; "A"; "C"; "B"; "C"; "C"; "C"|]
   let second = [|"A"; "B"; "C"|]
   let third  = [|"1"; "2"; "3"|]

   let rplc (x:string[]) (y:string[]) (z:string[]) = 
      first
      // |> Array.map (fun w -> Array.iter2 (fun x y -> (if w = x then y)) second third)

   let fourth = 
      rplc first second third

   printfn ""
   printfn "fourth: %A" fourth

   // Expected Result: fourth: [|"1"; "2"; "3"; "1"; "2"; "1"; "3"; "2"; "3"; "3"; "3"|]
   // Actual Result:   fourth: [|"A"; "B"; "C"; "A"; "B"; "A"; "C"; "B"; "C"; "C"; "C"|]

我的评论行失败,但我不知道为什么?

标签: arraysreplacef#matchunique

解决方案


最简单的方法是从第二个和第三个数组创建一个查找表,而不是映射第一个数组的每个元素,并将其用作键。

let first  = [|"A"; "B"; "C"; "A"; "B"; "A"; "C"; "B"; "C"; "C"; "C"|]
let second = [|"A"; "B"; "C"|]
let third  = [|"1"; "2"; "3"|]

let lookupTbl = Map(Array.zip second third) //create a Map/Dictionary from the zipped values

first
|> Array.map (fun x -> lookupTbl.[x]) //Use the first array's values as keys
//val it : string [] = [|"1"; "2"; "3"; "1"; "2"; "1"; "3"; "2"; "3"; "3"; "3"|]

TryFind如果您不确定所有密钥都存在,您也可以使用,但在您的情况下似乎没有必要。

您的原始案例不起作用,因为您试图if用作语句,所以它返回unit(因为如果 x 不等于 w 会发生什么)。

如果你想更接近你的原始结构,你可以模式匹配而不是 if,然后删除不匹配。Array.collect将数组数组折叠成一个数组。该match表达式执行if代码中的操作,但Some如果匹配则返回值,None否则返回值。None最后我们SomeArray.choose.

let rplc (x:string[]) (y:string[]) (z:string[]) = 
  first
  |> Array.collect (fun w -> 
                        Array.map2 (fun x y -> 
                                                match (w = x) with
                                                | true -> Some(y)
                                                | _ -> None ) second third)
  |> Array.choose id

let fourth = 
  rplc first second third

printfn ""
printfn "fourth: %A" fourth

// val fourth : string [] =
//   [|"1"; "2"; "3"; "1"; "2"; "1"; "3"; "2"; "3"; "3"; "3"|]
// val it : unit = ()

推荐阅读