我正在尝试在Rust中实现State单子(
似乎我需要在实例化“unit”中的“State”时明确指定闭包表达式的生命周期,但我不知道该怎么做,所以我需要帮助。谢谢。
State
实际上是一个包装器,它将原始状态作为输入并返回修改后的状态和一些结果的函数)。以下是如何在Haskell中实现 State
(为简洁起见,单子操作被重命名为 unit
和 bind
):data State s u = State { run :: s -> (u, s) }
-- return
unit :: u -> State s u
unit u = State $ \s -> (u, s)
-- (>>=)
bind :: State s u -> (u -> State s a) -> State s a
bind m f = State $ \s ->
let (u, s') = run m s
in run (f u) s'
所以我尝试用Rust重写它:
pub struct State<'r, S, U> {
priv run: 'r |S| -> (U, S)
}
pub fn unit<'r, S, U>(value: U) -> State<'r, S, U> {
State {
run: |state| (value, state)
}
}
实际上,我不确定run
字段的定义是否合法——said这是一个错误。
这段代码无法编译:
/some/path/lib.rs:31:12: 31:36 error: cannot infer an appropriate lifetime due to conflicting requirements
/some/path/lib.rs:31 run: |state| (value, state)
^~~~~~~~~~~~~~~~~~~~~~~~
/some/path/lib.rs:29:52: 33:2 note: first, the lifetime cannot outlive the block at 29:51...
/some/path/lib.rs:29 pub fn unit<'r, S, U>(value: U) -> State<'r, S, U> {
/some/path/lib.rs:30 State {
/some/path/lib.rs:31 run: |state| (value, state)
/some/path/lib.rs:32 }
/some/path/lib.rs:33 }
/some/path/lib.rs:31:12: 31:36 note: ...so that closure does not outlive its stack frame
/some/path/lib.rs:31 run: |state| (value, state)
^~~~~~~~~~~~~~~~~~~~~~~~
/some/path/lib.rs:29:52: 33:2 note: but, the lifetime must be valid for the lifetime &'r as defined on the block at 29:51...
/some/path/lib.rs:29 pub fn unit<'r, S, U>(value: U) -> State<'r, S, U> {
/some/path/lib.rs:30 State {
/some/path/lib.rs:31 run: |state| (value, state)
/some/path/lib.rs:32 }
/some/path/lib.rs:33 }
/some/path/lib.rs:30:5: 30:10 note: ...so that types are compatible (expected `State<'r,S,U>` but found `State<,S,U>`)
/some/path/lib.rs:30 State {
^~~~~
error: aborting due to previous error
似乎我需要在实例化“unit”中的“State”时明确指定闭包表达式的生命周期,但我不知道该怎么做,所以我需要帮助。谢谢。
编辑:不幸的是,我不能使用proc
(正如Vladimir建议的那样),因为一个State
可以被任意执行多次。
||
为非盒式闭包:||
相当于一个&Fn<...>
特质对象(对于一个假设的Fn
特质),也就是说,它已经被盒装成了一个特质对象,其中数据(在这种情况下是闭包环境)位于堆栈上。一个“非盒式闭包”是&x as &Fn<...>
中的x
,它目前还无法创建,但正在进行相关工作。(我认为这项工作比DST更相关。讨论的开始。) - huon