Advertisement
NLinker

Infinite recursion

Jul 3rd, 2018
377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.06 KB | None | 0 0
  1. // taken from https://play.rust-lang.org/?gist=cdf47bdfa00043671cdd574ed2380e66
  2. // article to read https://beachape.com/blog/2017/03/12/gentle-intro-to-type-level-recursion-in-Rust-from-zero-to-frunk-hlist-sculpting/
  3.  
  4. trait ScalarProduct<A> {
  5.     fn scalar_product(&self, second: &A) -> i64;
  6. }
  7.  
  8. struct Nil;
  9.  
  10. impl ScalarProduct<Nil> for Nil {
  11.     fn scalar_product(&self, _: &Nil) -> i64 {
  12.         0
  13.     }
  14. }
  15.  
  16. struct Cons<A> {
  17.     head: i64,
  18.     tail: A,
  19. }
  20.  
  21. impl<A> ScalarProduct<Cons<A>> for Cons<A>
  22.     where A: ScalarProduct<A>
  23. {
  24.     fn scalar_product(&self, second: &Self) -> i64 {
  25.         self.head * second.head + self.tail.scalar_product(&second.tail)
  26.     }
  27. }
  28.  
  29. fn main() {
  30.     let n = 15;
  31.     println!("{}", sp(n, 0, Nil, Nil));
  32. }
  33.  
  34. fn sp<A>(n: i64, i: i64, first: A, second: A) -> i64
  35.     where A: ScalarProduct<A>
  36. {
  37.     if n == 0 {
  38.         first.scalar_product(&second)
  39.     } else {
  40.         sp(
  41.             n - 1, i + 1,
  42.             Cons { head: 2 * i + 1, tail: first },
  43.             Cons { head: i * i, tail: second }
  44.         )
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement