Code Monkey home page Code Monkey logo

arts's Introduction

Arithmetic in Rust's Type System

Based on some basic ideas from math, we use deeply nested genenics to represent numbers and then apply traits like functions to do arithmetic! Here's how we'd multiply two numbers:

trait Mul {
    type Product;
}

impl<T> Mul for (T, Zero) {
    type Product = Zero;
}

impl<T> Mul for (Zero, Succ<T>) {
    type Product = Zero;
}

impl<T, U> Mul for (Succ<T>, Succ<U>)
where
    (T, Succ<U>): Mul,
    (Succ<U>, <(T, Succ<U>) as Mul>::Product): Add,
{
    // x * y = y + (x - 1) * y
    type Product = <(Succ<U>, <(T, Succ<U>) as Mul>::Product) as Add>::Sum;
}

Then doing <(encode!(***), encode!(****)) as Mul>::Product::VALUE would give the actual integer 12, even though everything in the previous expression is a type!

Here's a blog post that explains it in much more detail: Doing First Grade Math in Rust's Type System

License

This project (more like formula sheet) is licensed under the GNU General Public License v3.0, because math is for everyone.

arts's People

Contributors

fprasx avatar pheki avatar ludi317 avatar mgeier avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.