gpt4 book ai didi

ocaml - 你如何在 OCaml/ReasonML 中获取列表的一部分?

转载 作者:行者123 更新时间:2023-12-01 09:13:10 25 4
gpt4 key购买 nike

例如,在 Ruby 中,您可以执行以下操作:

list = ["foo", "bar", "baz", "qux", "quux", "corge"]
result = list[2..4]

result将包含 ["baz", "qux", "quux"] .

你会如何在 OCaml/ReasonML 中做到这一点?

最佳答案

没有用于切片列表的内置功能,但可以轻松完成。
由于我们有起点和终点,我们可以将问题分解为两部分。第一部分是到drop几个元素直到我们到达起点,第二部分是 take从起点到终点的几个元素。

let rec drop = (n, list) =>
switch (list) {
| [] => []
| [_, ...xs] as z => n == 0 ? z : drop(n - 1, xs)
};

let rec take = (n, list) =>
switch (list) {
| [] => []
| [x, ...xs] => n == 0 ? [] : [x, ...take(n - 1, xs)]
};

现在我们有了这两个函数,我们可以将它们组合起来,从起始点 drop(i, list) 开始删除初始元素。然后传递这个新列表以获取从起点到终点的元素
take(k - i + 1, drop(i, list));

总共
let slice = (list, i, k) => {

let rec drop = (n, list) =>
switch (list) {
| [] => []
| [_, ...xs] as z => n == 0 ? z : drop(n - 1, xs)
};

let rec take = (n, list) =>
switch (list) {
| [] => []
| [x, ...xs] => n == 0 ? [] : [x, ...take(n - 1, xs)]
};

take(k - i + 1, drop(i, list));
};

更好的方法是提供起点,然后提供范围而不是终点,因为在这里我们不限制终点应该大于起点
let slice = (list, start, range) => {

let rec drop = (n, list) =>
switch (list) {
| [] => []
| [_, ...xs] as z => n == 0 ? z : drop(n - 1, xs)
};

let rec take = (n, list) =>
switch (list) {
| [] => []
| [x, ...xs] => n == 0 ? [] : [x, ...take(n - 1, xs)]
};

take(range, drop(start, list));
};

关于ocaml - 你如何在 OCaml/ReasonML 中获取列表的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53015090/

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