根据第二个列表复制列表中的项目

编写一个函数,该函数根据第二个列表(指定要复制项目的次数)复制列表中的项目。

使用列表的功能编写方式在Ocaml中编写功能。

如果使用库函数-仅可用于O(1)计算复杂度。


例如:

duplicate [5;6;7] [0;2;5;3];;

返回:

[6;6;7;7;7;7;7]

到目前为止我已经发明的代码:

let duplicate (list1,list2)=
let rec read (list2,list1) = 
if List.hd list2 = 0 then read (List.tl list2,List.tl list1) else print (List.hd list2,List.hd list1)
let rec print (acc,num) =
num :: (print (acc-1,num));;

  • 首先,它无法编译,我有“语法错误” ...
  • 我不确定这些“嵌套”功能。
  • 我相信复杂性会更好。
style221 回答:根据第二个列表复制列表中的项目

在考虑此问题的答案时,应检查最简单的情况。即,如何将元素添加到列表x次。示例:

let rec add_elem_num_times num times lst =
  match times with
  | 0 -> lst
  | _ -> add_elem_num_times num (times - 1) (num::lst)

let ans = add_elem_num_times 5 3 (add_elem_num_times 3 8 [])

let () = List.iter (fun x -> Printf.printf "%d\n" x) ans

剩下的就是让它适用于许多元素。

本文链接:https://www.f2er.com/3156003.html

大家都在问