gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:36:59 25 4
gpt4 key购买 nike

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

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

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

我该怎么做?

最佳答案

与 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

关于F# 交换数据数组并获得正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8492939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com