在ocaml中的较小数组上递归拆分数组

时间:2017-05-21 09:03:30

标签: arrays ocaml

我试图在2个数组上以n长度递归分割数组,直到得到1个n元素的数组:

let rec split array = 
    if Array.length array = 1 then
        array
    else if Array.length array mod 2 = 0 then
        let a = Array.make (Array.length array /2) 0 in
        for i = 0 to Array.length a-1 do 
            a.(i) <- array.(i) done;
        let b = Array.make (Array.length array/2) 0 in 
        for i = Array.length a to Array.length array -1 do
            b.(i-Array.length a) <- array.(i) done;
        split a;
        split b;
    else
        let a = Array.make(Array.length array/2 +1) 0 in
        for i = 0 to Array.length a-1 do
            a.(i) <- array.(i) done;
        let b = Array.make (Array.length array/2) 0 in 
        for i = Array.length a to Array.length array -1 do
            b.(i-Array.length a) <- array.(i) done;
            split a;
            split b;


split [|3;2;4;1|];; 

该函数仅返回最后一个元素,但我希望它返回类似[|3|];[|2|];[|4|];[|1|]

的内容

1 个答案:

答案 0 :(得分:4)

如果你真的想通过分而治之来解决这个问题并递归地创建越来越小的数组,那么这将是一种编写它的方法,最终返回单例数组的列表:

let rec split = function
  | [||] -> []
  | [|x|] as a -> [a]
  | a ->
    let i = Array.length a / 2 in
    split (Array.sub a 0 i) @ split (Array.sub a i (Array.length a - i))

但是,当然,创建所有中间数组都过于复杂且效率低下。以下定义计算相同的列表,但更简洁,更有效:

let split a = Array.fold_right (fun x l -> [|x|]::l) a []