Ocaml从递归函数中返回一个列表
问题描述:
我想通过一个数组并返回一个int值列表(索引值),当数组中的值匹配true时。Ocaml从递归函数中返回一个列表
该数组是一个真/假值的布尔数组。
let get_elements (i:int)(b:bool) : int =
if b = true then (i::l)
else (())
;;
let rec true_list (b: bool array) : int list =
(fun i l -> get_elements i l)
;;
的语法是错误的我的代码,我困惑于究竟是如何返回ints.I列表只想要回那些阵列中的真实元素的索引。
答
您在get_elements中引用'l',但它不在该函数的范围内。
下面是一个使用裁判的整数列表(一个可变的列表)的方法:
boolarray = [|true; false; true; false; false; true|] ;;
type ilist = (int list) ref ;;
let intlist() : ilist = ref [] ;;
let push (l: ilist) (x: int) : unit = l := x::(!l) ;;
let lst = intlist() ;;
Array.iteri (fun i b -> if b = true then (push lst i)) boolarray ;;
!lst ;; (* => int list = [5; 2; 0] *)
或者,如果你宁愿避免裁判(这通常是一个好主意),这是清洁:
let get_true_list (b: bool array) : int list =
let rec aux i lst =
if (i = Array.length b) then lst else
(if b.(i) = true then (aux (i+1) (i::lst)) else (aux (i+1) lst)) in
aux 0 [] ;;
(* using boolarray defined above *)
get_true_list boolarray ;; (* => int list = [5; 2; 0] *)
答
I present an example which does not use state, avoids the 'if then else' construct making it easier to read and verify. let mylist = [| true; false; false; true; false; true |] in let get_true_indexes arr = let a = Array.to_list arr in let rec aux lst i acc = match lst with | [] -> List.rev acc | h::t when h = true -> aux t (i+1) (i::acc) | h::t -> aux t (i+1) acc in aux a 0 [] in get_true_indexes mylist
或用[电池](http://batteries.forge.ocamlcore.org/),'Array.fold_lefti(李乐趣IB - >若b的话,我::李李其他)[]' 。另外,我认为在你的'ref'例子中,你应该真的把ref封装在一个函数中,因为在这里它可能暗示ref始终是全局的,这比所需要的要难得多。 – gasche 2011-04-27 04:31:42
我很高兴你改变了你的答案,不涉及引用。 – nlucaroni 2011-04-27 14:54:23