Ocaml returning a list from a recursive function
I want to go through an array and return a list of ints (the value of ind开发者_C百科exes) when a value in the array matches true.
The array is a boolean array of just true/false values.
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)
;;
The syntax is wrong for my code and I am confused on exactly how to return a list of ints.I only want to return the indexes of those elements that are true in the array.
You refer to 'l' in get_elements, but it's not in the scope of that function.
Here's an approach using a ref to an integer list (a mutable list):
 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] *)
Or, if you'd rather avoid refs (which is usually a good idea) this is cleaner:
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
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论