【问题标题】:How to find index of an Array element in OCaml如何在 OCaml 中查找 Array 元素的索引
【发布时间】:2015-11-28 17:58:07
【问题描述】:

我正在尝试在 ocaml 中查找整数数组元素的索引。如何递归地做到这一点。 示例代码:let a = [|2; 3; 10|];; 假设我想返回数组 a 中 3 的索引。任何帮助表示赞赏。我是 OCaml 编程新手

【问题讨论】:

    标签: functional-programming ocaml ocaml-batteries


    【解决方案1】:
    type opt = Some of int | None;;
    
    let find a i =
      let rec find a i n =
        if a.(n)=i then Some n
        else find a i (n+1)
      in
      try 
        find a i 0
       with _ -> None
    ;;
    

    测试

    # find a 3;;
    - : int option = Some 1
    # find [||] 3;;
    - : int option = None
    # find a 12;;
    - : int option = None
    

    【讨论】:

      【解决方案2】:

      您使用索引递归地检查每个元素

      let rec find a x n =
      if a.(n) = x then n 
      else find a x (n+1);;
      
      find a x 0;;
      

      如果元素不是数组的一部分,则会引发异常(当 n 大于数组的长度时)。

      【讨论】:

      • 我更好地理解了这个答案。可能其他答案更好,但我仍然需要了解更多才能理解它们。而且我认为可以通过检查是否 n > (Array.length a -1) 然后将“某个整数值表示未找到”作为函数 find 中的第一个表达式来避免引发异常。
      【解决方案3】:
      let f xs x =
        let i = ref (-1) in
        let () = Array.iteri (fun n elt -> if x = elt then i := n else ()) xs in
        !i
      

      如果元素不在列表中,则返回值为-1

      【讨论】:

        猜你喜欢
        • 2013-03-13
        • 2013-10-19
        • 1970-01-01
        • 2011-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多