sharkdp / numbat

A statically typed programming language for scientific computations with first class support for physical dimensions and units
https://numbat.dev
Apache License 2.0
1.16k stars 50 forks source link

Usage as a Rust library for runtime string parsing #580

Open Keavon opened 4 days ago

Keavon commented 4 days ago

This project is really cool! I know it is described as its own language, but would it be feasible to use Numbat as a Rust library for parsing user-provided math expression strings into dimensioned values at runtime? I'm looking for a replacement for https://github.com/rekka/meval-rs which supports unit conversions and dimensional analysis instead of just simplifying scalar math expressions. I'd basically like to give it a string as input and receive a number paired with unit(s) so that Graphite users can type expressions like 3*8px or 360°/.5s into number input boxes and it simplifies to something like 24 px or 720°/sec. Would such a use case be feasible? Thanks :)

sharkdp commented 4 days ago

Thank you for the feedback. I think it should be possible to do this today, in principle. The numbat crate is a library that can be embedded into applications.

There are a few caveats though. The API of the numbat crate is very much in flow, so you would have to be okay with future breaking changes. It has not really been designed as a "user" facing library, so far. It also lacks a high level API that makes it convenient to do things like what you plan to do. That said, I think it should be possible to do what you want in a few lines of code (start with creating a numbat::Context). Let me know if you need help with that.

There are a few other things to consider. Numbat is not really a lightweight dependency. You basically pull in a full compiler/interpreter including the full "standard library"/prelude. Everything is designed to be customizable (you could use your own prelude with custom units, for example). But you might wish to exclude certain parts of numbat for your use case (eg through cargo features), but this is not yet possible.

All that said, I would really appreciate you feedback if you plan to experiment with numbat-as-a-library.