List Ocaml从递归函数返回列表

List Ocaml从递归函数返回列表,list,recursion,ocaml,List,Recursion,Ocaml,我想遍历一个数组,当数组中的值与true匹配时,返回一个int(索引值)列表 该数组是一个仅包含真/假值的布尔数组 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) ;; 对于我的代码,语法是错误的,我

我想遍历一个数组,当数组中的值与true匹配时,返回一个int(索引值)列表

该数组是一个仅包含真/假值的布尔数组

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)
;;

对于我的代码,语法是错误的,我对如何返回整数列表感到困惑。我只想返回数组中为真的那些元素的索引

您在get_元素中引用了“l”,但它不在该函数的范围内

下面是一种使用整数列表(可变列表)的引用的方法:

或者,如果您希望避免引用(这通常是一个好主意),这会更干净:

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] *)
我给出了一个不使用状态的示例,它避免了“if-then-else”构造,使其更易于阅读和验证。 让mylist=[true;false;false;true;false;true;true]in 让我们获取真正的索引arr= 设a=Array.to_list arr in 让rec aux lst i acc=将lst与 |[]->List.rev acc |h::t当h=真->辅助t(i+1)(i::acc) |h::t->辅助t(i+1)acc 在里面 辅助a 0[] 在里面 获取\u true\u索引我的列表
或者使用,
Array.fold_lefti(fun li i b->if b then i::li else li)[
。另外,我认为在你的
ref
示例中,你应该真正将ref封装在一个函数中,因为这里可能建议将ref始终作为一个全局函数,这比必要的要难看得多。我很高兴你用一个不涉及引用的函数更改了你的答案。
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