Ocaml中的列表倒序 [英] List reversing in Ocaml
本文介绍了Ocaml中的列表倒序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我们假设元素从0开始计数,那么如何反转列表的子列表.我希望解决方案是手动编码"的.我在完成这项任务时遇到了很大的问题.
How to reverse even sublists of a list if we assume that we count elements from 0. I want the solution to be "manually-coded". I've got a big problem with this task.
例如:
Function([[1;2;3] ; [2;3] ; [1;2;3] ; [5;6;7]])
返回:
([[3;2;1] ; [2;3] ; [3;2;1] ; [5;6;7]])
我已经创建了一个可以反转单个列表的函数:
I already created a function that reverse a single list:
let rev =
let rec rev_append acc l =
match l with
[] -> acc
| h::t -> rev_append (h::acc) t in
fun l -> rev_append [] l;;
但是现在我被困住了.
But now i am stuck.
推荐答案
let rev_list l =
let rec rev_acc acc = function
| [] -> acc
| hd::tl -> rev_acc (hd::acc) tl
in
rev_acc [] l
let rev_even l =
let rec rev i acc = function
| [] -> rev_list acc
| hd::tl ->
if i mod 2 = 0 then rev (i+1) ((rev_list hd)::acc) tl
else rev (i+1) (hd::acc) tl
in
rev 0 [] l
请注意,它们都是尾递归的
note that they are all tail-recursive
修改
对诺兰的建议
尾递归在函数式编程和OCaml中非常重要.请记住.
tail-recursive is quite important in functional programming and OCaml. Please bear in mind.
这篇关于Ocaml中的列表倒序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文