Create a byte array with dynamic size in F#

跟風遠走 提交于 2019-12-05 16:44:42

问题


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 do is to do the same thing in F#. I have searched for how to do it and looked for it in the documentation. I think that I'm probably using the wrong search terms because I can't find out how.

What I've found so far is that Array.create can be used like this:

let b = Array.create x ( new Byte() )

Is there another way to do it which is more similiar to the way it can be done in C# and Java?


回答1:


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#.




回答2:


A closest F# analog would be Array.zeroCreate:

let b: byte [] = Array.zeroCreate x

Instead of implicit array elements initialization to 0 bytes on Java and C# platforms F# makes the initial value of array elements obvious.

As to dynamic size of b in F# it is defined once by x value at the allocation and cannot be changed later by changing x, similarly to C#/Java,.




回答3:


let b = Array.create<byte> x 0uy  //Array.zeroCreate<byte> x



回答4:


What do you mean?

F# has a syntax different from C# and Java, you are using the Array module to let him create an array with an initializer. Nothing strange, one language is functional while the other is imperative so these differences are indeed needed.

According to the F# language specs you can't declare something that is uninitialized (unless using specific patterns as the Option type which are just exploits that allow you to express the uninitialized concept without really having it), that's why you have to pass an initializer for elements in the array.



来源:https://stackoverflow.com/questions/11063962/create-a-byte-array-with-dynamic-size-in-f

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