F#交换数据数组并获得正确的结果

时间:2011-12-13 16:51:09

标签: f#

let highs = [| 2; 4; 6 |]
let lows = [| 1; 5; 10 |]

我想从上面得到2个数组:如果highs中的元素小于lows中的相应元素,则交换它们。所以,我可以得到最后的2个数组:

let trueHighs = [| 2; 5; 10 |]
let trueLows = [| 1; 4; 6 |]

我该怎么做?

3 个答案:

答案 0 :(得分:5)

与JaredPar的答案类似但更简单:

let trueHighs, trueLows =        
    Array.zip highs lows
    |> Array.map (fun (x, y) -> if x >= y then (x, y) else (y, x))
    |> Array.unzip

另一个更简洁的版本:

let trueHighs, trueLows =        
    (highs, lows)
    ||> Array.map2 (fun x y -> if x >= y then (x, y) else (y, x))    
    |> Array.unzip

答案 1 :(得分:3)

以下是您应该使用的代码:

let n = highs.Length
let trueHighs = Array.init n (fun i -> max highs.[i] lows.[i])
let trueLows = Array.init n (fun i -> min highs.[i] lows.[i])

如果表现非常关键,那么你可能会采取必要的方法。

let n = highs.Length
let trueHighs = Array.zeroCreate n
let trueLows = Array.zeroCreate n
for i = 0 to n-1 do
  let hi = highs.[i]
  let lo = lows.[i]
  if hi > lo then
    trueHighs.[i] <- hi
    trueLows.[i] <- lo
  else
    trueHighs.[i] <- lo
    trueLows.[i] <- hi

答案 2 :(得分:0)

尝试以下

let trueHighs, trueLows = 
  let zipped = 
    highs
    |> Seq.ofArray
    |> Seq.zip (lows |> Seq.ofArray)
    |> Seq.map (fun (x, y) -> min x y, max x y)
  let lows = zipped |> Seq.map fst |> Array.ofSeq
  let highs = zipped |> Seq.map snd |> Array.ofSeq
  highs, lows