How to make a wacky math calculator? (Preferably in C ++, but others are ok too).

I would like to know how to do something more low-level in C ++ that will allow me to do some "crazy" math operations. Specifically, my two questions are:

1) How can I define my own math symbol that the compiler will be able to recognize in my code. In other words, I'm not looking to parse the string from the user, but rather the compiler has recognized it as a new mathematical operation.

   ex:   3 {+} 4   will actually do 3 – 4  etc.

      

2) How to determine custom number from ASCII character. For example, define the character #, which should be recognized by the compiler as 18 (ie 00010010 in binary).

   ex:   18 {+} # = 18 - 18 = 0

      

If possible, I would like to be able to do the above two things on the arm of the compiler. The solutions in C ++, Java, C, Python and Objective-C are fine. Just let me know what language your solution is in. Thank!:)

+3


source to share


2 answers


In my comment I said that this implies C ++ macros; if what you want is not much more complicated than what you are showing, this should do the trick. Defining operators as macros should work for simple search / replace cases, but may not work well for complex expressions and certain symbols.

From my head, I think that what you want is possible in Haskell using infix functions as operators, but it might not be that easy for a beginner. Look Lah and find infixr

. However, you need a basic knowledge of Haskell.



Edit with Zeta example, you can run it in ghci

:

(<+>) = (-) -- operator definition
(<*>) = (/)

answer = 42
answer <+> 12 -- prints 30
answer <*> 7 -- prints 6.0

      

+2


source


You can wrap types in a class and then overload operators. I came up with a minimal example for the "wacky" add ( +

becomes -

). But if you want to use POD you need to use preprocessor, there is no other way.



#include <iostream>
using namespace std;

template<typename T>
class wacky
{
    T val_;
public:
    wacky(T val = {}): val_(val){};

    // let define a conversion operator
    template<typename S>
    operator S (){return val_;}

    // we don't need asignment operator and copy ctors

    // stream operators
    friend ostream& operator<<(ostream& os, const wacky& rhs)
    {
        return os << rhs.val_;
    }

    // the += operator
    wacky& operator+=(const wacky& rhs)
    {
        val_ -= rhs.val_; // wacky!
        return *this;
    }

    // and the wacky operator+
    friend wacky operator+(wacky lhs, const wacky& rhs)
    {
        return lhs+=rhs;
    }
};

int main()
{
    wacky<int> a,b;
    a = 10;
    b = 15;

    // a and b behave now like PODs
    // implicit conversions work etc
    double wacky_sum = a + b; 
    cout << wacky_sum << endl; // -5
}

      

+2


source







All Articles