DEV Community

Discussion on: Functional Programming in Rust

Collapse
 
ryuheechul profile image
Heechul Ryu

I was wondering how this code work as tail rec function and I discovered that it is not recursive at all.

impl Factor for i64_t {
    fn factorial_tail_rec(val: i64_t) -> Self {
        val
    }

    fn factorial(num: i64_t) -> Self {
        match num {
            0 => 1,
            _ => num * Self::factorial_tail_rec(num - 1)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

You could tell by asserting like this:

let result: i64_t = Factor::factorial(4); 
assert_eq!(24, result);

// will give you this kind of error below:

/*
thread 'xxx' panicked at 'assertion failed: `(left == right)`
  left: `24`,
 right: `12`'
*/
Enter fullscreen mode Exit fullscreen mode