我尝试学习F#,此时我尝试将简单的C#函数转换为F#
在某些方面我坚持示例var compressedData = new byte[memoryStream.Length];
< C#
这里是完整的c#函数
public static string CompressString(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
var memoryStream = new MemoryStream();
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
{
gZipStream.Write(buffer, 0, buffer.Length);
}
memoryStream.Position = 0;
var compressedData = new byte[memoryStream.Length];
memoryStream.Read(compressedData, 0, compressedData.Length);
var gZipBuffer = new byte[compressedData.Length + 4];
Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
return Convert.ToBase64String(gZipBuffer);
}
这里是我的半翻译版本
let compress(text:string)=
let buffer = Encoding.UTF8.GetBytes(text)
use memoryStream = new MemoryStream()
let gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true)
gZipStream.Write(buffer, 0, buffer.Length)
memoryStream.Position <- Convert.ToInt64(0)
let compressedData = Array.init memoryStream.Length(fun i -> byte) //< Here i stuck
memoryStream.Read(compressedData, 0, compressedData.Length)
use gZipBuffer = (compressedData.Length + 4)
过去三天我在谷歌搜索解决了我的问题,但我没有找到任何解决方案。 我希望有人可以帮助我:) 非常感谢您提前
答案 0 :(得分:3)
编辑:修正了翻译以便编译(现在应该可以使用)。
open System
open System.IO
open System.IO.Compression
open System.Text
let compressString (text : string) =
let buffer = Encoding.UTF8.GetBytes text
using (new MemoryStream ()) <| fun memoryStream ->
using (new GZipStream(memoryStream, CompressionMode.Compress, true)) <| fun gzipStream ->
gzipStream.Write (buffer, 0, Array.length buffer)
memoryStream.Position <- 0L
let compressedData = Array.zeroCreate (int memoryStream.Length)
let numBytesRead = memoryStream.Read (compressedData, 0, compressedData.Length)
if numBytesRead = compressedData.Length then
let gzipBuffer = Array.zeroCreate (compressedData.Length + 4)
Buffer.BlockCopy (compressedData, 0, gzipBuffer, 4, compressedData.Length)
Buffer.BlockCopy (BitConverter.GetBytes buffer.Length, 0, gzipBuffer, 0, 4)
Convert.ToBase64String gzipBuffer
else
failwithf "Tried to read %i bytes but was only able to read %i."
compressedData.Length numBytesRead
答案 1 :(得分:1)
您正在寻找Array.zeroCreate
。
let compressedData = Array.zeroCreate (int memoryStream.Length)