【问题标题】:return the nth element of a list in OCaml?返回 OCaml 中列表的第 n 个元素?
【发布时间】:2012-04-05 10:24:38
【问题描述】:

我是 Ocaml 的新手,只是想确定如何执行一个简单的功能,例如使用递归函数返回列表的第 n 个元素?

原型如get_nth (list, n)int list * int -> int

例如get_nth ([1,2,3], 1) -> 2

谢谢

【问题讨论】:

  • 这听起来确实像一个家庭作业问题。如果您展示了一些您尝试过的代码并没有像您希望的那样工作,那将会有所帮助。

标签: list recursion functional-programming ocaml


【解决方案1】:

我读过here,使用Result 而不是引发错误会更好,因为您不必使用try ... with。 (代码由@Omar 编辑)

let rec get_nth mylist index = match mylist with
    | [] -> Error "empty list"
    | first::rest -> 
        if index = 0 then Ok first 
        else get_nth rest (index-1)
;;

let result [1; 2; 3] 2 in 
    match result with
    | Error reason -> print_string reason
    | Ok num -> print_int num
;;

ResultCore.Std 的一部分,如果我没记错的话。

【讨论】:

    【解决方案2】:

    (在我看来)不使用元组的更简单的解决方案是:

    let rec get_nth mylist index = match mylist with
        | [] -> raise (Failure "empty list")
        | first::rest -> 
            if index = 0 then first 
            else get_nth rest (index-1)
    ;;
    

    【讨论】:

    • 我会将此作为正确答案。在 Ocaml 函数中使用元组作为参数不是很习惯,需要分配。
    【解决方案3】:

    您可能没有注意到,但List.nth 函数已经存在于List module 中。

    如果你想用递归来写:

    let rec get_nth = function
        | [], _ -> raise (Failure "get_nth")
        | _, n when n < 0 -> raise (Invalid_argument "get_nth")
        | x::_, 0 -> x
        | x::xs, n -> get_nth(xs, n-1)
    

    【讨论】:

      【解决方案4】:

      像这样使用元组作为参数在 OCaml 中并不常见。通常你会使用柯里化并像这样定义你的函数:

      let get_nth list n = ...
      

      这将具有签名'a list -&gt; int -&gt; 'a。另请注意,您在此处有一个 'a 参数,这意味着,没有真正的理由将您的函数仅限制为 int。

      现在让我们看看这个问题。如果你想得到第零个元素,你的函数会是什么样子?

      let get_nth list 0 = List.head list (* this is not actually valid in OCaml *)
      

      现在,如果您有一个函数可以从 m 项列表中获取第 n 个元素 (NB n > m),您如何使用该函数来构建另一个函数,该函数从 m+ 列表中获取第 n+1 个元素1个元素?让 n+1 个元素的函数为 get_nth'

      let get_nth' list n' = get_nth (List.tail list) (n'-1)
      

      现在您需要做的就是将两者结合起来,您就完成了。我将把最后一部分留给你。

      如果您遵循此建议,您会得到比实际情况更复杂的东西。然而,这样更容易理解发生了什么。

      【讨论】:

      • 不幸的是,恐怕您的尝试比它需要的更令人困惑。 Ocaml 模式匹配本身就具有很强的视觉解释性。
      猜你喜欢
      • 2014-12-20
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-12
      • 2018-05-27
      • 1970-01-01
      相关资源
      最近更新 更多