OCaml - declaring n-dimensional arrays

眉间皱痕 提交于 2019-12-01 17:55:01

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)))

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!