gpt4 book ai didi

list - 整数的Ocaml列表到整数列表的列表(与展平相反)

转载 作者:行者123 更新时间:2023-12-02 07:05:21 24 4
gpt4 key购买 nike

带有整数列表,例如:

[1;2;3;4;5;6;7;8;9]

如何从上面创建一个整数列表,所有新列表都具有相同的指定长度?

例如,我需要从:
[1;2;3;4;5;6;7;8;9] to [[1;2;3];[4;5;6];[7;8;9]]

要拆分的数字为3?

谢谢你的时间。

最佳答案

所以你真正想要的是一个类型函数

val split : int list -> int -> int list list

需要一个整数列表和一个子列表大小。哪一个更普遍呢?
val split : 'a list -> int -> 'a list list

这里是实现:
let split xs size =
let (_, r, rs) =
(* fold over the list, keeping track of how many elements are still
missing in the current list (csize), the current list (ys) and
the result list (zss) *)
List.fold_left (fun (csize, ys, zss) elt ->
(* if target size is 0, add the current list to the target list and
start a new empty current list of target-size size *)
if csize = 0 then (size - 1, [elt], zss @ [ys])
(* otherwise decrement the target size and append the current element
elt to the current list ys *)
else (csize - 1, ys @ [elt], zss))
(* start the accumulator with target-size=size, an empty current list and
an empty target-list *)
(size, [], []) xs
in
(* add the "left-overs" to the back of the target-list *)
rs @ [r]

如果您为此获得加分,请告诉我! ;)

关于list - 整数的Ocaml列表到整数列表的列表(与展平相反),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13262057/

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