Last active
January 25, 2022 11:29
-
-
Save tralamazza/4c5fdd561e54b052ae61650cfdecfd3b to your computer and use it in GitHub Desktop.
Peano in (ugly) Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://godbolt.org/z/Yr8nKvWxW