当我尝试编译以下代码时:
fn main() {
(...)
let mut should_end = false;
let mut input = Input::new(ctx);
input.add_handler(Box::new(|evt| {
match evt {
&Event::Quit{..} => {
should_end = true;
}
_ => {}
}
}));
while !should_end {
input.handle();
}
}
pub struct Input {
handlers: Vec<Box<FnMut(i32)>>,
}
impl Input {
pub fn new() -> Self {
Input {handlers: Vec::new()}
}
pub fn handle(&mut self) {
for a in vec![21,0,3,12,1] {
for handler in &mut self.handlers {
handler(a);
}
}
}
pub fn …Run Code Online (Sandbox Code Playgroud) 编辑:看来我在这里称之为"懒惰",不是"懒惰"的意思.我不确定适当的术语是什么.有些人说我正在寻找的术语是"富有成效的",但在这种情况下我找不到该术语的任何定义.我想要的是一个可以使用无限列表的函数.我将使用我对该术语的最佳理解,将任何"懒惰"变为"富有成效".
功能
f a = a:(f (a-1))
Run Code Online (Sandbox Code Playgroud)
以富有成效的方式生成无限列表.因为a:在每个其他评估面前.
这意味着你可以做到take 10 (f 0)并且很好.
但是,功能
h a = h (a ++ (map (-1) a))
Run Code Online (Sandbox Code Playgroud)
没有效率,永远不会终止.由于a ++是另一个评估内部.因此head (h [0]),即使很明显它是0 ,你也做不到.
我是否可以采用一般策略将非生产性功能转变为生产性功能?
具体来说,我试图解决的问题是在懒洋洋地消耗它的第二个参数时使下面的效果:
binarily a [] = a
binarily a (b:bs) = binarily (a ++ map (b+) a) bs
Run Code Online (Sandbox Code Playgroud) 编辑:我总共犯了4个错误.
在第5行,我有"''",这没有任何意义.
在第9行,我有"map(asciiRotC)".这应该是"map(asciiRotC n)"
在第13行,我有"x:xs.这应该是"(x:xs)".
在最后一行我有"asciiRotWith 0(+1)".这应该是"......(+ 1)0"
这是我的完整代码(该文件名为asciiRot.hs):
import System.Environment
import System.IO
asciiRotC :: Int -> Char -> Char
asciiRotC _ '' = ''
asciiRotC 0 msg = msg
asciiRotC n msg = toEnum (33 + (n + (fromEnum msg) - 33) `mod` 93) :: Char
asciiRot :: Int -> String -> String
asciiRot n msg = map (asciiRotC) msg
asciiRotWith :: (Int->Int) -> Int -> String -> String
asciiRotWith _ _ "" = ""
asciiRotWith f acc x:xs …Run Code Online (Sandbox Code Playgroud)