Struct Solution

Source
pub struct Solution;
Expand description

用 Rust 写代码,无法对错误视而不见。 只有在最后调用的时候假设输入都是合法的。

代码看起来挺长,其实很简单,代码结构也很清晰。

主要思路是递归,先 tokenize 输入,这里因为用了 Iterator tokenize 返回的时候是没有遍历的。

lisp 语法规则很简单,直接看 eval()

主要逻辑在 eval() 里,很简单,就是处理 let 语句稍微需要注意下,进入 eval_let() 之前需要入栈,eval_let() 返回后需要出栈。

eval_let() 里循环处理赋值语句,最后表达式求值返回。

另外要说的是,Rust 实现的思路一般不像 C 那样直接处理下标,而是利用高级别的抽象(例如 Iterator)这种去处理,只要遍历一次。

栈的实现,没有在进入下一个作用域的时候拷贝变量空间,而是把当前作用域的变量名对应的键值对入栈,出栈的时候先删除当前作用域里的变量,再从整个栈里恢复变量空间。

Implementations§

Source§

impl Solution

Source

pub fn evaluate(expression: String) -> i32

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.