2

我尝试学习 F#,此时我尝试将一个简单的 C# 函数转换为 F#,在某些方面我停留在 example var compressedData = new byte[memoryStream.Length];< C# here the full c# function

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)

最近三天我在谷歌上搜索以解决我的问题,但我没有找到任何解决方案。我希望这里有人可以帮助我:) 非常感谢你提前

4

2 回答 2

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
于 2012-09-21T17:54:40.817 回答
1

你正在寻找Array.zeroCreate.

let compressedData = Array.zeroCreate (int memoryStream.Length)
于 2012-09-21T17:44:13.517 回答