OCaml-声明n维数组 [英] OCaml - declaring n-dimensional arrays
问题描述
我想在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屋!