创建一个字节数组,在F#中动态大小 [英] Create a byte array with dynamic size in F#

查看:187
本文介绍了创建一个字节数组,在F#中动态大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#和Java的字节数组可以这样创建

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

byte[] b = new byte[x];

其中, X 表示数组的大小。我想要做的是做同样的事情在F#中。我已经寻找如何做到这一点,并在文件中寻找它。我想,我可能使用了错误的搜索词,因为我无法找出如何。

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.

我到目前为止已经发现的是, Array.create 可以这样使用:

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

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

有另一种方式做到这一点是更类同的方式,它可以在C#和Java?

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

推荐答案

我想你想创建一个未初始化数组并填入它:

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)

这是你通常做在C#/ Java,它是unidiomatic在F#的方式。想想吧;如果你忘了初始化一些元素,你必须处理噩梦。

在大多数情况下,你总是可以从的阵列模块或阵列COM prehension:

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

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

看看这个MSDN页面;它包含了F#中使用数组有用的信息。

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

这篇关于创建一个字节数组,在F#中动态大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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