Skip to content

Instantly share code, notes, and snippets.

@tralamazza
Last active January 25, 2022 11:29
Show Gist options
  • Save tralamazza/4c5fdd561e54b052ae61650cfdecfd3b to your computer and use it in GitHub Desktop.
Save tralamazza/4c5fdd561e54b052ae61650cfdecfd3b to your computer and use it in GitHub Desktop.
Peano in (ugly) Rust
#![allow(unused)]
use std::ops;
/*
This example serves no purpose, it implements peano arithmetic both as types and values.
It's an excuse to overload the + operator.
*/
#[derive(Debug, Default, Clone, Copy)]
struct Zero;
#[derive(Debug, Default, Clone, Copy)]
struct Succ<A>(A);
impl<A> ops::Add<A> for Zero {
type Output = A;
fn add(self, rhs: A) -> Self::Output {
rhs
}
}
// dont ask me to explain this thing
impl<A, B> ops::Add<B> for Succ<A>
where
A: ops::Add<B>,
Succ<A::Output>: Default,
{
type Output = Succ<A::Output>;
fn add(self, _: B) -> Self::Output {
Succ::<A::Output>::default()
}
}
pub fn main() {
let zero = Zero;
let one = Succ(zero);
let two = Succ(one);
println!("two = {:?}", two);
println!("0 + 0 = {:?}", zero + zero);
println!("0 + 1 = {:?}", zero + one);
println!("1 + 0 = {:?}", one + zero);
println!("1 + 2 = {:?}", one + two);
println!("2 + 2 = {:?}", two + two);
}
@tralamazza
Copy link
Author

tralamazza commented Jan 25, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment