我正在尝试在Python中使用C中创建完全相同的 Mersenne Twister(MT).
基于Lib/random.py以及阅读文档,似乎整个MT _random实现在C中实现:
The underlying implementation in C is both fast and threadsafe.
Run Code Online (Sandbox Code Playgroud)
通过谷歌搜索"Python _random",我在GitHub上找到了这个页面,这似乎正是我想要的,虽然它似乎不是正式的.
我使用了这个源代码并删除了除MT本身,种子函数和双重创建函数之外的所有内容.我还改变了一些类型,使整数为32位.
首先,这是许可证信息(只是为了安全)
/* Random objects */
/* ------------------------------------------------------------------
The code in this module was based on a download from:
http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html
It was modified in 2002 by Raymond Hettinger as follows:
* the principal computational lines untouched.
* renamed genrand_res53() to random_random() and wrapped
in python calling/return code.
* genrand_int32() and the helper functions, …Run Code Online (Sandbox Code Playgroud) 迭代器方法take_while将闭包作为其参数.
例如:
fn main() {
let s = "hello!";
let iter = s.chars();
let s2 = iter.take_while(|x| *x != 'o').collect::<String>();
// ^^^^^^^^^^^^^
// closure
println!("{}", s2); // hell
}
Run Code Online (Sandbox Code Playgroud)
这对于简单的闭包很好,但是如果我想要一个更复杂的谓词,我不想直接在take_while参数中写它.相反,我想从函数返回闭包.
我似乎无法让这个工作.这是我天真的尝试:
fn clos(a: char) -> Box<Fn(char) -> bool> {
Box::new(move |b| a != b)
}
fn main() {
// println!("{}", clos('a')('b')); // <-- true
// ^--- Using the closure here is fine
let s = "hello!";
let mut iter = s.chars();
let s2 = iter.take_while( …Run Code Online (Sandbox Code Playgroud) 下面的代码给出错误“无法移出借用的内容”。我知道这里已经有很多关于此的问题。我认为每个使用 Rust 的人都会在某一时刻发现自己正试图弄清楚所有权究竟发生了什么。我想我知道这里发生了什么以及如何解决它,我只是不知道如何在这种特殊情况下使用参考。如果有更惯用的方法来完成我正在尝试的事情,请在评论中告诉我。
我可以看到我试图在哪里获得所有权,但我不确定如何使用引用。
让我们看一个最小的例子:
/* I define two shape structs. The main point here is that they
are not default copyable, unlike most primitive types */
struct Circle {
center_x: f64,
center_y: f64,
r: f64,
}
struct Square {
center_x: f64,
center_y: f64,
length: f64,
}
/* this enum will be a container for shapes because we don't know
which shape we might need. */
enum Shape {
// these are scoped differently, so it's okay.
Circle(Circle),
Square(Square),
} …Run Code Online (Sandbox Code Playgroud)