Ocaml从递归函数返回一个列表

时间:2011-04-26 23:57:26

标签: list recursion ocaml

当数组中的值匹配true时,我想通过一个数组并返回一个int列表(索引的值)。

数组是一个只有true / false值的布尔数组。

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

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

2 个答案:

答案 0 :(得分:3)

你在get_elements中引用'l',但它不在该函数的范围内。

这是一种使用ref到整数列表(可变列表)的方法:

 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] *)

答案 1 :(得分:2)

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
相关问题