F#Two Arrays - 第二个阵列上的索引过滤的第一个阵列产品

时间:2017-12-14 09:37:00

标签: arrays indexing filter f#

我有三个数组 - 第一个是一个浮点数组,第二个是一个字符串数组, fltr 是一个字符串数组。我需要根据第二个数组中的匹配索引是否包含过滤器数组元素中的所有字符来生成第一个数组中元素的乘积:

module SOQN = 

   open System

   let first   = [| 2.00;   3.00;   5.00;   7.00;   11.00 |]
   let second  = [| "ABCD"; "ABCE"; "ABDE"; "ACDE"; "BCDE" |]
   let fltr    = [| "AC";   "BD";   "CE" |]

   let result =
      first
      |> Array.filter second // filter for elements containing characters in second array
      |> Seq.reduce (fun x y -> x * y)

   // Expected Result: let result = [| 42.00; 110.00; 231.00 |]

如何生成产品数组?

2 个答案:

答案 0 :(得分:2)

像这样的东西

let first   = [| 2.00;   3.00;   5.00;   7.00;   11.00 |]
let second  = [| "ABCD"; "ABCE"; "ABDE"; "ACDE"; "BCDE" |]
let fltr    = "AC"

Array.zip first second
|> Array.filter (fun (_, s) ->
    Seq.forall (fun c -> s.Contains (string c)) fltr)
|> Array.map fst
|> Array.reduce (*)

答案 1 :(得分:1)

以下代码段(虽然不是惯用语)提供了我正在寻求的完整答案,并包含@ xuanduc987解决方案:

module SOANS = 

open System

let first   = [| 2.00;   3.00;   5.00;   7.00;   11.00 |]
let second  = [| "ABCD"; "ABCE"; "ABDE"; "ACDE"; "BCDE" |]
let fltr    = [| "AC";   "BD";   "CE" |]

let filterProduct (first:float[]) (second:string[]) (fltr:string) = 
    Array.zip first second
    |> Array.filter (fun (_, s) ->
        Seq.forall (fun c -> s.Contains (string c)) fltr)
    |> Array.map fst
    |> Array.reduce (*)

let third = 
    [for i in [0..fltr.Length - 1] do
        yield (filterProduct first second fltr.[i])]
    |> List.toArray

printfn "Third: %A" third

// Expected Result: Third: [| 42.0; 110.0; 231.0 |]
// Actual Result    Third: [| 42.0; 110.0; 231.0 |]