首页 > 解决方案 > ocaml 列表到数组数组

问题描述

我正在尝试将具有指定宽度的列表转换为数组数组。例如,我想转换这个:

int list = [97; 114; 110; 97; 117; 100; 2]

int array array = [| [|97; 114; 110|]; [|97; 117; 100|]; [|2; 0; 0|] |]

我不习惯 ocaml,所以我尝试使用此代码:

let split list width =
  let rec aux i acc = function
    | [] -> List.rev acc, []
    | h :: t as l -> 
      if i = 0 
      then List.rev acc, l
      else aux (i-1) (h :: acc) t  in
aux width [] list;;

标签: listocaml

解决方案


我会在这个问题上倒退。

首先,我将创建一个函数,该函数接受一个列表、一个填充值和必须应用填充的次数。像这样的东西:

val add_padding: int -> int -> int list -> int list

接下来我将创建一个函数,它接受一个列表和一个宽度并返回一个新列表和传入的列表的其余部分......如果传入的列表太短,这应该会失败。就像是:

val create_new_list: int -> 'a list -> 'a list * 'a list 

使用这两个功能,您应该能够拆分输入列表。


推荐阅读