Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays F#三个数组-用新值替换原始数组中的唯一值_Arrays_Replace_F#_Match_Unique - Fatal编程技术网

Arrays F#三个数组-用新值替换原始数组中的唯一值

Arrays F#三个数组-用新值替换原始数组中的唯一值,arrays,replace,f#,match,unique,Arrays,Replace,F#,Match,Unique,我有三个数组-第一、第二和第三。第二个包含第一个的唯一值,第三个包含通过映射到第二个来替换第一个的新值,如下所示: 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:st

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

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"|]

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

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

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
一些带有
数组的
选项包装器

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

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