7

我有以下代码尝试使用通常的 MaybeBuilder 从网络流中读取可能不完整的数据(例如图像数据):

let image = maybe {
    let pos = 2 //Initial position skips 2 bytes of packet ID
    let! width, pos = readStreamAsInt 2 pos
    let! height, pos = readStreamAsInt 2 pos
    let! data, pos = readStream (width*height) pos
    advanceInStream pos
    return {width = width; height = height; pixels = data}
}

因此,如果数据尚未到达 NetworkStream,readStream[asInt] [numBytes] [offset] 函数将返回 Some [data] 或 None。AdvanceInStream 函数在读取整个网络数据包时执行。

我想知道是否有某种方法可以编写一些自定义计算表达式构建器来隐藏从其用户传递的 pos,因为它总是相同的 - 我在流中读取一些数据和位置并将其作为最后一个参数传递给下一个读取函数。

PS MaybeBuilder 使用:

type MaybeBuilder() =    
    member x.Bind(d,f) = Option.bind f d
    member x.Return d = Some d
    member x.ReturnFrom d = d
    member x.Zero() = None
let maybe = new MaybeBuilder()

聚苯乙烯

再想一想,似乎我必须使 pos 可变,因为阅读中可能出现“for”或“while”循环。简单让!使用 pos Bind 阴影效果很好,但是如果你在循环中添加阅读,你就不能保持不变性,对吧?任务变得微不足道。

4

1 回答 1

4

@bytebuster 在自定义计算表达式的可维护性方面做得很好,但我仍然认为我演示了如何将Stateand Maybemonad 组合为一个。

在“传统”语言中,我们对组合值(例如整数)有很好的支持,但是在开发解析器时会遇到问题(从二进制流中生成值本质上是解析)。对于解析器,我们希望将简单的解析器函数组合成更复杂的解析器函数,但这里的“传统”语言通常缺乏良好的支持。

在函数式语言中,函数和值一样普通,因为值可以组合,显然函数也可以。

首先让我们定义一个StreamReader函数。AStreamReader接受一个StreamPosition(流 + 位置)并产生一个更新的StreamPosition和一个StreamReaderResult(读取值或失败)。

type StreamReader<'T> = 
  StreamReader of (StreamPosition -> StreamPosition*StreamReaderResult<'T>)

(这是最重要的一步。)

我们希望能够将简单StreamReader的函数组合成更复杂的函数。我们要保持的一个非常重要的属性是组合操作是“关闭的”,StreamReader这意味着组合的结果是一个新的StreamReader,而它又可以无限地组合。

为了读取图像,我们需要读取宽度和高度,计算乘积并读取字节。像这样的东西:

let readImage = 
  reader {
    let! width  = readInt32 
    let! height = readInt32 
    let! bytes  = readBytes (width*height)

    return width, height, bytes
  }

因为组合被关闭readImage是一个StreamReader<int*int*byte[]>.

为了能够StreamReader像上面那样进行组合,我们需要定义一个计算表达式,但在我们这样做之前,我们需要定义操作ReturnBindfor StreamReader。事实证明Yield,拥有也很好。

module StreamReader =
  let Return v : StreamReader<'T> =
    StreamReader <| fun sp -> 
      sp, (Success v)

  let Bind (StreamReader t) (fu : 'T -> StreamReader<'U>) : StreamReader<'U> =
    StreamReader <| fun sp -> 
      let tsp, tr = t sp
      match tr with
      | Success tv ->
        let (StreamReader u) = fu tv
        u tsp
      | Failure tfs -> tsp, Failure tfs

  let Yield (ft : unit -> StreamReader<'T>) : StreamReader<'T> =
    StreamReader <| fun sp -> 
      let (StreamReader t) = ft ()
      t sp

Return是微不足道的,因为StreamReader应该返回给定的值并且不更新StreamPosition.

Bind更具挑战性,但描述了如何将两个StreamReader函数组合成一个新函数。Bind运行第一个StreamReader函数并检查结果,如果失败则返回失败,否则使用StreamReader结果计算第二个函数StreamReader并在更新流位置上运行。

Yield只需创建StreamReader函数并运行它。YieldF# 在构建计算表达式时使用。

最后让我们创建计算表达式构建器

type StreamReaderBuilder() =
  member x.Return v   = StreamReader.Return v
  member x.Bind(t,fu) = StreamReader.Bind t fu
  member x.Yield(ft)  = StreamReader.Yield ft

let reader = StreamReaderBuilder ()

StreamReader现在我们构建了组合功能的基本框架。此外,我们还需要定义原始StreamReader函数。

完整示例:

open System
open System.IO

// The result of a stream reader operation is either
//  Success of value
//  Failure of list of failures
type StreamReaderResult<'T> =
  | Success of 'T
  | Failure of (string*StreamPosition) list

and StreamPosition =
  {
    Stream    : byte[]
    Position  : int
  }

  member x.Remaining = max 0 (x.Stream.Length - x.Position)

  member x.ReadBytes (size : int) : StreamPosition*StreamReaderResult<byte[]> =
    if x.Remaining < size then
      x, Failure ["EOS", x]
    else
      let nsp = StreamPosition.New x.Stream (x.Position + size)
      nsp, Success (x.Stream.[x.Position..(x.Position + size - 1)])

  member x.Read (converter : byte[]*int -> 'T) : StreamPosition*StreamReaderResult<'T> =
    let size = sizeof<'T>
    if x.Remaining < size then
      x, Failure ["EOS", x]
    else
      let nsp = StreamPosition.New x.Stream (x.Position + size)
      nsp, Success (converter (x.Stream, x.Position))

  static member New s p = {Stream = s; Position = p;}

// Defining the StreamReader<'T> function is the most important decision
//   In this case a stream reader is a function that takes a StreamPosition 
//   and produces a (potentially) new StreamPosition and a StreamReadeResult
type StreamReader<'T> = StreamReader of (StreamPosition -> StreamPosition*StreamReaderResult<'T>)

// Defining the StreamReader CE
module StreamReader =
  let Return v : StreamReader<'T> =
    StreamReader <| fun sp -> 
      sp, (Success v)

  let Bind (StreamReader t) (fu : 'T -> StreamReader<'U>) : StreamReader<'U> =
    StreamReader <| fun sp -> 
      let tsp, tr = t sp
      match tr with
      | Success tv ->
        let (StreamReader u) = fu tv
        u tsp
      | Failure tfs -> tsp, Failure tfs

  let Yield (ft : unit -> StreamReader<'T>) : StreamReader<'T> =
    StreamReader <| fun sp -> 
      let (StreamReader t) = ft ()
      t sp

type StreamReaderBuilder() =
  member x.Return v   = StreamReader.Return v
  member x.Bind(t,fu) = StreamReader.Bind t fu
  member x.Yield(ft)  = StreamReader.Yield ft

let reader = StreamReaderBuilder ()

let read (StreamReader sr) (bytes : byte[]) (pos : int) : StreamReaderResult<'T> =
  let sp    = StreamPosition.New bytes pos
  let _, sr = sr sp
  sr

// Defining various stream reader functions
let readValue (converter : byte[]*int -> 'T) : StreamReader<'T> =
  StreamReader <| fun sp -> sp.Read converter

let readInt32 = readValue BitConverter.ToInt32
let readInt16 = readValue BitConverter.ToInt16
let readBytes size : StreamReader<byte[]> = 
  StreamReader <| fun sp -> 
    sp.ReadBytes size

let readImage = 
  reader {
    let! width  = readInt32 
    let! height = readInt32 
    let! bytes  = readBytes (width*height)

    return width, height, bytes
  }

[<EntryPoint>]
let main argv = 
  // Sample byte stream
  let bytes   = [|2;0;0;0;3;0;0;0;1;2;3;4;5;6|] |> Array.map byte
  let result  = read readImage bytes 0

  printfn "%A" result

  0
于 2015-06-13T15:39:01.297 回答