Create a byte array with dynamic size in F#

前端 未结 4 1841
被撕碎了的回忆
被撕碎了的回忆 2021-02-20 07:16

In C# and Java a byte array can be created like this

byte[] b = new byte[x];

where x denotes the size of the array. What I want to

4条回答
  •  遇见更好的自我
    2021-02-20 07:37

    I think you would want to create an uninitialized array and fill it later:

    let arr = Array.zeroCreate 10
    for i in 0..9 do
       arr.[i] <- byte(i*i)
    

    It's the way you normally do in C#/Java, which is unidiomatic in F#. Think about it; if you forget to initialize some elements, you have to deal with null nightmares.

    In almost all cases, you can always replace the above procedure by high-order functions from Array module or array comprehension:

    let arr = Array.init 10 (fun i -> byte(i*i))
    

    or

    let arr = [| for i in 0..9 do -> byte(i*i)|]
    

    Take a look at this MSDN page; it contains useful information about using Array in F#.

提交回复
热议问题