fork download
  1. use std::fmt;
  2. use std::iter;
  3.  
  4.  
  5. struct LinearFunctionIterator {
  6. fun: LinearFunction,
  7. x: i32,
  8. stop: i32,
  9. }
  10.  
  11. impl LinearFunctionIterator {
  12. fn new(fun: LinearFunction, begin: i32, stop: i32) -> LinearFunctionIterator {
  13. LinearFunctionIterator {
  14. fun: fun,
  15. x: begin,
  16. stop: stop,
  17. }
  18. }
  19. }
  20.  
  21. impl iter::Iterator for LinearFunctionIterator {
  22. type Item = f64;
  23.  
  24. fn next(&mut self) -> Option<Self::Item> {
  25. if self.x == self.stop {
  26. return None
  27. }
  28.  
  29. let result = self.fun.feed(self.x as f64);
  30.  
  31. if self.x < self.stop {
  32. self.x += 1;
  33. }
  34. else {
  35. self.x -= 1;
  36. }
  37.  
  38. return Some(result);
  39. }
  40. }
  41.  
  42.  
  43. struct LinearFunction {
  44. a: f64,
  45. b: f64,
  46. }
  47.  
  48. impl LinearFunction {
  49. fn new(a: f64, b: f64) -> LinearFunction {
  50. LinearFunction {
  51. a: a,
  52. b: b,
  53. }
  54. }
  55.  
  56. fn feed(&self, x: f64) -> f64 {
  57. self.a * x + self.b
  58. }
  59. }
  60.  
  61. impl fmt::Display for LinearFunction {
  62. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  63. write!(f, "f(x) = {} * x + {}", self.a, self.b)
  64. }
  65. }
  66.  
  67. impl iter::IntoIterator for LinearFunction {
  68. type Item = f64;
  69. type IntoIter = LinearFunctionIterator;
  70.  
  71. fn into_iter(self) -> Self::IntoIter {
  72. LinearFunctionIterator::new(self, 0, 10)
  73. }
  74. }
  75.  
  76.  
  77. fn main() {
  78. let fun = LinearFunction::new(2.0, 1.0);
  79. println!("{}", fun);
  80.  
  81. for y in fun.into_iter() {
  82. println!("{}", y.round());
  83. }
  84. }
Success #stdin #stdout 0s 4472KB
stdin
Standard input is empty
stdout
f(x) = 2 * x + 1
1
3
5
7
9
11
13
15
17
19