list - 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;;
解决方案
我会在这个问题上倒退。
首先,我将创建一个函数,该函数接受一个列表、一个填充值和必须应用填充的次数。像这样的东西:
val add_padding: int -> int -> int list -> int list
接下来我将创建一个函数,它接受一个列表和一个宽度并返回一个新列表和传入的列表的其余部分......如果传入的列表太短,这应该会失败。就像是:
val create_new_list: int -> 'a list -> 'a list * 'a list
使用这两个功能,您应该能够拆分输入列表。
推荐阅读
- html - 大多数浏览器会根据设置的语言自动替换一些字符?
- java - 为什么 HashSet 添加对象的顺序不像代码中的那样?
- javascript - 平滑向下滑动以锚定文档加载
- reactjs - 使用 Clarifai 的 API 和 react 的 useState 和 useEffect 时出现 400 Bad Request API CALL
- azure-devops - Azure DevOps 管道变量组无法列出 Key Vault
- python - 如何在基于函数的视图中返回多个自定义过滤器
- xml - 加载 XML 有多个命名空间到 SQL usnig SSIS
- javascript - 渐进式地创建数组 js
- android - 我正在尝试在 recyclerview 中从 firebase 检索数据?每当我单击按钮时,应用程序就会崩溃
- python - mongodb使用python向现有数组添加一个新字段