What's the most interesting constant program you can run?

Hi! Just for fun everyone.

It would appear that

const fn main() { }

is a valid, compiling and running program in stable Rust. :smiley:

What's the most interesting program you have written or are willing to write and demonstrate in "constant main" Rust?!

This sport is just for fun and there are two classes you can enter into:

  1. Using only stable Rust features
  2. Using experimental features.

Entries must use a const fn main function!

I'll start with this simple program in stable Rust: playground link

Any computation the type system can do can be used here. As it’s Turing-complete, there’s really no limit. Here’s an implementation of Forth that runs at compile-time on stable, for instance (not mine):

3 Likes

Now I'm curious what parts of this experiment can be made into the const fns, thanks for idea!

More bending of the rules; a nonterminating FizzBuzz implemenation:

use std::fmt::Debug;

struct ConstMain;

impl Debug for ConstMain {
    fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        let mut x:u64 = 1;
        loop {
            x += 1;
            println!("{}", match x {
                fb if fb % 15 == 0 => "FizzBuzz".into(),
                f  if f  %  3 == 0 => "Fizz".into(),
                b  if  b %  5 == 0 => "Buzz".into(),
                x => x.to_string()
            });
            // Comment out for infinite loop
            // if x > 200 { std::process::exit(0); }
        }
    }
}

const
fn main() -> Result<(), ConstMain> {
    Err(ConstMain)
}

(Playground)

11 Likes

Nice trick! This way, you can in fact "smuggle" any calculation out of the const fn main(), since they'll be running in the std runtime, which is non-const context.

6 Likes

This does not use const fn main but it is fun to read. Constant time and space to find duplicates.

1 Like

I wonder, how can something “infinite” be const? Maybe I need a revision of my definition of const.

The challenge was writing a program with a const fn main declaration. I realized that you can have a non-const Debug implementation that will be called after main returns a constant Err(...).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.