OCaml-声明n维数组 [英] OCaml - declaring n-dimensional arrays

查看:115
本文介绍了OCaml-声明n维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在ocaml中创建3维数组.这是我尝试做的事情:

I want to create 3-dimensional array in ocaml. Here's what I tried to do:

let dp = Array.make n (Array.make n (Array.make k (-1))

但是它不起作用-更改值dp [0] [0] [0]会更改所有值dp [i] [j] [0].那么如何创建具有不同数组的矩阵,而不是具有相同数组的副本?

However it doesn't work - changing a value dp[0][0][0] changes all values dp[i][j][0]. So how to create matrix with distinct arrays, not with copies of the same one?

推荐答案

Array.make n v只会复制第二个参数n次.换句话说,它将以循环的方式将其分配给每个元素.由于数组(以及所有其他堆分配的值)都是通过引用传递的,因此所有单元格都将指向同一数组.您需要使用Array.init函数,该函数将为每个元素调用用户提供的函数:

Array.make n v will just replicate the second argument n times. In other words, it will assign it in a cycle to each element. Since arrays (as well as all other heap-allocated values) are passed by reference, all cells will point to the same array. You need to use the Array.init function, that will call user provided function for each element:

let dp = Array.init n (fun _ -> Array.init n (fun _ -> (Array.make k 0)))

但是,对于真正的多维数字代码,您不应使用数组,而应使用Bigarray模块.这是示例:

But, for real multidimensional numeric code, you shouldn't use arrays, but instead use Bigarray module. Here is the example:

open Bigarray
let dp = Array3.create int c_layout 3 3 3
dp.{0,0,0} <- 1

这篇关于OCaml-声明n维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆