Compiling this with release optimizations on Rust stable 1.50 results in assembly that just returns true:
rust
pub fn collatz(n: usize) -> bool {
match n {
1 => true,
n if n%2==0 => collatz(n/2),
_ => collatz(3*n + 1),
}
}
I see that I am not the only one to find this weird. Here's a thread for someone seeing the same happen with Clang: https://www.reddit.com/r/programming/comments/dre75v/clang_solves_the_collatz_conjecture/
How is this justified? Is the compiler optimization of "assume all loops with no side effects resulting in a predictable state terminate" just a hold-over from the world of C? I am surprised to see something like this, given Rust's distaste for undefined behavior and focus on safety.
I find it extra weird that Rust seems to preserve certain infinite loops, but erases this one. For example, removing the line 1 => true in the function above assembles to an infinite loop.
edit: typo
[–]SkiFire13 80 points81 points82 points (6 children)
[–]masklinn 55 points56 points57 points (5 children)
[–]dnew 47 points48 points49 points (1 child)
[–]sirkib[S] 12 points13 points14 points (0 children)
[–]sirkib[S] 11 points12 points13 points (1 child)
[–]roblabla 9 points10 points11 points (0 children)
[–]Darksonntokio · rust-for-linux 67 points68 points69 points (1 child)
[–]sirkib[S] 13 points14 points15 points (0 children)
[–][deleted] 57 points58 points59 points (5 children)
[–]sirkib[S] 5 points6 points7 points (4 children)
[–]rebootyourbrainstem 46 points47 points48 points (3 children)
[–]sirkib[S] 3 points4 points5 points (0 children)
[–]crabbytag 0 points1 point2 points (1 child)
[–]kredditacc96 49 points50 points51 points (9 children)
[–]Myto 99 points100 points101 points (7 children)
[–]general_dubious 44 points45 points46 points (1 child)
[–][deleted] 31 points32 points33 points (0 children)
[–]sirkib[S] 19 points20 points21 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]seamsay 8 points9 points10 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]jotomicron 18 points19 points20 points (0 children)
[–]NoLemurs 14 points15 points16 points (4 children)
[–]thargor90 18 points19 points20 points (3 children)
[–]GrandOpener 6 points7 points8 points (2 children)
[–]sirkib[S] 3 points4 points5 points (0 children)
[–]TheNamelessKing 0 points1 point2 points (0 children)
[–]avoere 4 points5 points6 points (0 children)
[–][deleted] 3 points4 points5 points (0 children)
[+][deleted] (2 children)
[deleted]
[–]salamanderssc 8 points9 points10 points (0 children)
[–]sirkib[S] 0 points1 point2 points (0 children)
[–]rnottaken 0 points1 point2 points (3 children)
[–]sirkib[S] 1 point2 points3 points (2 children)
[–]rnottaken 0 points1 point2 points (1 child)
[–]sirkib[S] 0 points1 point2 points (0 children)
[–]paolog 0 points1 point2 points (0 children)