gpt4 book ai didi

OCaml : How to create a list of n 1's in

转载 作者:行者123 更新时间:2023-12-05 08:19:03 25 4
gpt4 key购买 nike

以下 Python 代码在 OCaml 中的等价物是什么?

lst = [0] * N

在我看来,OCaml 没有为列表重载 *

我写了下面的函数

let makeList i = if i = 0 then [] else 0 :: makeList (i-1)

我可以使用 for 循环做一些事情或者让代码更短吗?

最佳答案

OCaml 标准库形成了一个最小的代数,适合在其之上构建用户库。您应该考虑使用一些可用的社区库。其中有很多,Batteries、Core、Extlib、Containers,仅举几例。如果有疑问,我会建议使用 Core 库,至少因为当前的技术水平 OCaml Book是用这个库编写的。在 Core 中有一个 List.init 函数,可以满足您的需要:

open Core.Std
List.init 10 ~f:(const 0);;
- : int list = [0; 0; 0; 0; 0; 0; 0; 0; 0; 0]

还有一个范围列表,可以制作iota列表:

List.range 0 10;;
- : int list = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9]

安装核心

opam install core

要在顶层使用它,请使用coretop 程序(与核心一起安装)。要编译程序,请使用 corebuild,例如,假设您的代码在 example.ml 中:

corebuild example.native

关于OCaml : How to create a list of n 1's in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36568189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com