【问题标题】:F# Three Arrays - Replace Unique Values In Original Array With New ValuesF# 三个数组 - 用新值替换原始数组中的唯一值
【发布时间】:2018-10-19 01:10:29
【问题描述】:

我有三个数组 - 第一个、第二个和第三个。 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"|]

我的注释行失败,但我不知道为什么?

【问题讨论】:

  • 你应该从第二个和第三个列表创建一个字典/映射,然后使用第一个列表作为键。

标签: arrays replace f# match unique


【解决方案1】:

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

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。最后,我们用Array.choose 去掉了NoneSome 选项包装器。

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 = ()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 2020-01-16
    • 1970-01-01
    • 2011-04-19
    • 2021-01-27
    • 1970-01-01
    • 2014-04-15
    相关资源
    最近更新 更多