Eri*_*ric 5 f# ocaml haskell yield iterate
此代码来自一篇名为"Lazy v.Permal"的论文.它是一种解耦数据流的生产者和消费者的方法.我理解代码的Haskell部分,但O'Caml/F#让我不知所措.由于以下原因,我不理解此代码:
对于将参数作为参数作为异常并返回单位的函数,我可以期待什么样的行为?
消费者如何投射到特定的例外?(那是什么意思?)
什么是消费者的例子?
module SimpleGenerators
type 'a gen = unit -> 'a
type producer = unit gen
type consumer = exn -> unit (* consumer will project into specific exception *)
type 'a transducer = 'a gen -> 'a gen
let yield_handler : (exn -> unit) ref =
ref (fun _ -> failwith "yield handler is not set")
let iterate (gen : producer) (consumer : consumer) : unit =
let oldh = !yield_handler in
let rec newh x =
try
yield_handler := oldh
consumer x
yield_handler := newh
with e -> yield_handler := newh; raise e
in
try
yield_handler := newh
let r = gen () in
yield_handler := oldh
r
with e -> yield_handler := oldh; raise e
Run Code Online (Sandbox Code Playgroud)
我对这篇论文不熟悉,所以其他人可能会更有启发性。与此同时,这里有一些快速答案/猜测。
类型的函数exn -> unit基本上是一个异常处理程序。
异常可以包含数据。它们与多态变体非常相似——即,您可以随时添加新的异常,并且它可以充当数据构造函数。
看起来消费者将寻找特定的异常来为其提供所需的数据。其他人只会重新加注。因此,它只是着眼于可能的异常空间的投影(我猜)。