gpt4 book ai didi

F# 计算表达式透明状态通过 Bind 传递

转载 作者:行者123 更新时间:2023-12-04 15:33:14 25 4
gpt4 key购买 nike

我有以下代码尝试使用通常的 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,因为它总是相同的 - 我在流中读取一些数据和位置并将其作为最后一个参数传递给下一个读取函数。

附言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 阴影效果很好,但是如果您在循环中添加阅读,您就无法保持不变性,对吗?那么这个任务就变得微不足道了。

最佳答案

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

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

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

首先让我们定义一个 StreamReader功能。一个 StreamReader需要一个 StreamPosition (流 + 位置)并生成更新的 StreamPosition和一个 StreamReaderResult (读取值或失败)。

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

(这是最重要的一步。)

我们喜欢能够编写简单的 StreamReader函数转换成更复杂的函数。我们要维护的一个非常重要的属性是,compose 操作在 StreamReader 下是“关闭的”。意味着组合的结果是一个新的 StreamReader反过来可以无休止地组成。

为了读取图像,我们需要读取宽度和高度,计算乘积并读取字节。像这样的东西:
let readImage = 
reader {
let! width = readInt32
let! height = readInt32
let! bytes = readBytes (width*height)

return width, height, bytes
}

因为作文已关闭 readImageStreamReader<int*int*byte[]> .

为了能够作曲 StreamReader像上面一样,我们需要定义一个计算表达式,但在此之前我们需要定义操作 ReturnBindStreamReader .原来 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
ReturnStreamReader 一样微不足道应该返回给定的值并且不更新 StreamPosition .
Bind有点挑战性,但描述了如何组合两个 StreamReader功能成一个新的。 Bind运行第一个 StreamReader函数并检查结果,如果失败则返回失败,否则使用 StreamReader计算第二个 StreamReader 的结果并在更新流位置上运行它。
Yield只是创建 StreamReader函数并运行它。 Yield在构建计算表达式时由 F# 使用。

最后让我们创建计算表达式构建器
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

关于F# 计算表达式透明状态通过 Bind 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30818901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com