【发布时间】:2018-10-18 19:35:54
【问题描述】:
我正在尝试模仿Parsing a simple imperative language (Haskell) 的第 3 部分。特别是,我正在考虑使用基于堆栈的语言而不是命令式语言,并且我正在尝试使用惯用的 Rust 代码来表示数据。
假设您想要制作一个小的(非常小的)stack based language,它有一些基本的算术运算,没有用户定义的函数,并且可以处理十进制数和整数。比如:
1 2 +
-> Stack contains: 3
发生了什么事?从左到右读取,将 1 和 2 压入堆栈,+ 会压出 1 和 2,然后将 3 (= 1 + 2) 压入堆栈。
我的想法是考虑3 需要解析的“原语”类型。你有整数、十进制数和函数。此外,十进制和整数都是“名词”,而函数是“动词”。所以当执行一个程序时,我的想法是你可以通过扩展 Result<T, E> 枚举的想法在 Rust 中表示这些想法。我想出了以下方案:
enum Noun {
Integer(i64),
Decimal(f64)
}
enum Primitive<T> {
Noun(T),
Verb(Fn(Vec<Noun>) -> Noun),
}
// Not really important, just giving a main so it can be ran
fn main() {
println!("Hello, world!");
}
换句话说,原语要么是Noun,要么是Verb,而Noun要么是整数,要么是浮点数。
但是,这会导致:
error[E0277]: the trait bound `std::ops::Fn(std::vec::Vec<Noun>) -> Noun + 'static: std::marker::Sized` is not satisfied
--> main.rs:8:10
|
8 | Verb(Fn(Vec<Noun>) -> Noun),
| ^^^^^^^^^^^^^^^^^^^^^^ `std::ops::Fn(std::vec::Vec<Noun>) -> Noun + 'static` does not have a constant size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `std::ops::Fn(std::vec::Vec<Noun>) -> Noun + 'static`
= note: only the last field of a struct may have a dynamically sized type
error: aborting due to previous error(s)
在 Rust 中执行此操作的标准方法是什么?
【问题讨论】:
标签: rust