List 基于第二个列表复制列表中的项目
编写一个函数,该函数基于第二个列表复制列表中的项目,该列表指定项目的复制次数 以使用列表编程的函数方式在Ocaml中编写函数 If库函数-只能与O(1)计算复杂度一起使用List 基于第二个列表复制列表中的项目,list,duplicates,ocaml,List,Duplicates,Ocaml,编写一个函数,该函数基于第二个列表复制列表中的项目,该列表指定项目的复制次数 以使用列表编程的函数方式在Ocaml中编写函数 If库函数-只能与O(1)计算复杂度一起使用 例如: 返回: 到目前为止我发明的代码: let replicate(列表1、列表2)= 让rec读取(列表2,列表1)= 如果List.hd list2=0,则读取(List.tl list2,List.tl list1)或打印(List.hd list2,List.hd list1) 让记录打印(acc,num)= n
例如: 返回:
到目前为止我发明的代码:
let replicate(列表1、列表2)=
让rec读取(列表2,列表1)=
如果List.hd list2=0,则读取(List.tl list2,List.tl list1)或打印(List.hd list2,List.hd list1)
让记录打印(acc,num)=
num::(打印(acc-1,num));;
- 首先,它没有编译,我有“语法错误”李>
- 我不确定这些“嵌套”函数李>
- 我相信复杂性会更好
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
剩下的只是让它对许多元素起作用。“不起作用”不是一个非常有用的问题描述。请更具体一点。如果第一个列表比第二个列表长,会发生什么情况?比方说,我们不允许出现这种情况。但是,也许有可能针对这些数据保护代码?好吧,如果需要两个独立的列表,就像我在问题中所写的那样?两个独立的列表?一个列表将提供元素,另一个将提供次数。如果你看看我的解决方案,你会注意到它需要一个元素和一个数字(次数的数字),这两个值都可以从列表中获得。
[6;6;7;7;7;7;7]
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