繁体   English   中英

Ocaml从递归函数返回列表

[英]Ocaml returning a list from a recursive function

我想遍历一个数组,并在数组中的值匹配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)
;;

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

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

或者,如果您希望避免使用refs(通常是个好主意),则此方法更干净:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM