作业帮助将迭代函数转换为递归函数

发布于 2024-08-07 20:28:31 字数 883 浏览 2 评论 0原文

对于作业,我以递归方式编写了以下代码。它采用向量数据类型和向量的列表,并计算两个向量的接近度。这个方法工作得很好,但我不知道如何做递归版本。

let romulus_iter (x:vector list) (vec:vector) = 
  let vector_close_hash = Hashtbl.create 10 in 
  let prevkey = ref 10000.0 in (* Define previous key to be a large value since we intially want to set closefactor to prev key*)
  if List.length x = 0 then
    {a=0.;b=0.}
  else
    begin
      Hashtbl.clear vector_close_hash; 
      for i = 0 to (List.length x)-1 do
        let vecinquestion = {a=(List.nth x i).a;b=(List.nth x i).b} in
        let closefactor = vec_close vecinquestion vec in
        if (closefactor < !prevkey) then 
          begin
            prevkey := closefactor;
            Hashtbl.add vector_close_hash closefactor vecinquestion
          end
      done; 
      Hashtbl.find vector_close_hash !prevkey
    end;;

For an assignment, i have written the following code in recursion. It takes a list of a vector data type, and a vector and calculates to closeness of the two vectors. This method works fine, but i don't know how to do the recursive version.

let romulus_iter (x:vector list) (vec:vector) = 
  let vector_close_hash = Hashtbl.create 10 in 
  let prevkey = ref 10000.0 in (* Define previous key to be a large value since we intially want to set closefactor to prev key*)
  if List.length x = 0 then
    {a=0.;b=0.}
  else
    begin
      Hashtbl.clear vector_close_hash; 
      for i = 0 to (List.length x)-1 do
        let vecinquestion = {a=(List.nth x i).a;b=(List.nth x i).b} in
        let closefactor = vec_close vecinquestion vec in
        if (closefactor < !prevkey) then 
          begin
            prevkey := closefactor;
            Hashtbl.add vector_close_hash closefactor vecinquestion
          end
      done; 
      Hashtbl.find vector_close_hash !prevkey
    end;;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倾城花音 2024-08-14 20:28:31

一般的递归等效项

for i = 0 to (List.length x)-1 do
    f (List.nth x i)
done

是这样的:

let rec loop = function
  | x::xs -> f x; loop xs
  | [] -> ()

请注意,就像 for 循环一样,此函数仅返回单位,尽管您可以定义一个类似的递归函数来返回有意义的值(事实上,这就是大多数函数所做的)。您还可以使用 List.iter,这仅适用于您应用不纯函数的情况,该函数不会返回对列表中的每个项目有意义的任何内容:

List.iter f x

The general recursive equivalent of

for i = 0 to (List.length x)-1 do
    f (List.nth x i)
done

is this:

let rec loop = function
  | x::xs -> f x; loop xs
  | [] -> ()

Note that just like a for-loop, this function only returns unit, though you can define a similar recursive function that returns a meaningful value (and in fact that's what most do). You can also use List.iter, which is meant just for this situation where you're applying an impure function that doesn't return anything meaningful to each item in the list:

List.iter f x
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文