likebike / fasteval

Fast and safe evaluation of algebraic expressions
https://crates.io/crates/fasteval/
MIT License
267 stars 26 forks source link

Support additional number bases #3

Open Stupremee opened 4 years ago

Stupremee commented 4 years ago

It would be very helpful if you can specify numbers in other bases, e.g. hexadecimal (0xFF) or binary (0b1001), and convert them via functions like in Python. (hex(255) -> 0xFF, bin(2) -> 10)

likebike commented 4 years ago

Great idea. I'll try to add this soon.

Stupremee commented 4 years ago

I can add this if it's okay.

likebike commented 4 years ago

I can add this if it's okay.

Sure, you can if you want to. You mostly just need to modify the read_const() function: https://github.com/likebike/fasteval/blob/master/src/parser.rs#L345

Stupremee commented 4 years ago

Yep already saw it

likebike commented 4 years ago

As far as the idea about hex()/bin()/... functions goes, that's going to be a bit complicated. Those functions would need to produce strings, not numbers, and they could only be used as arguments within a print() function (because that is the only place where strings are allowed).

...So i suggest that we first just implement the parsing of numeric literals ( 0xFF, 0b010101, 0o746 ), and ignore the string formatting for now.

likebike commented 4 years ago

Instead of using functions like hex()/bin()/oct()/..., another way to do the string formatting of alternate bases is by using printf-style formatting codes, like this: print("hex=%x dec=%d oct=%o bin=%b", 100, 100, 100, 100)

I like Go's choice of formatting codes: https://golang.org/pkg/fmt/#hdr-Printing

I am already planning to add printf codes to print(). In fact, my Go implementation of this library already has that feature, but dynamic string formatting is not a built-in feature in Rust, so I will need to implement it myself.

Stupremee commented 4 years ago

That’s a good idea 👍. Rust formatting has support for hex, oct and binary. Probably you can use that.

likebike commented 4 years ago

The Rust formatting is really nice, but it is compile-time only. fasteval needs runtime formatting. Maybe we can find a way to re-use the Rust formatting infrastructure at runtime.

Stupremee commented 4 years ago

Can't you just use the format macro?

likebike commented 4 years ago

All macros are evaluated at compile-time. We need a solution that can perform string formatting at run-time.

Stupremee commented 4 years ago

Ohh, yes you are right.

Stupremee commented 4 years ago

I don't have much time at the moment. So the PR will take around a week.

likebike commented 4 years ago

No problem. Take your time -- I appreciate your help.