]> www.ginac.de Git - ginac.git/blob - doc/examples/mystring.cpp
primpart_content: correctly handle monomials.
[ginac.git] / doc / examples / mystring.cpp
1 /**
2  * @file mystring.cpp Example of extending GiNaC: writing new classes
3  */
4 #include <iostream>
5 #include <string>   
6 #include <stdexcept>
7 using namespace std;
8
9 #include <ginac/ginac.h>
10 using namespace GiNaC;
11
12 class mystring : public basic
13 {
14         GINAC_DECLARE_REGISTERED_CLASS(mystring, basic)
15 public:
16         mystring(const string &s);
17         ex eval(int level) const;
18 private:
19         string str;
20
21 protected:
22         void do_print(const print_context &c, unsigned level = 0) const;
23
24 };
25
26 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(mystring, basic,
27   print_func<print_context>(&mystring::do_print))
28
29 // ctors
30 mystring::mystring() { }
31 mystring::mystring(const string &s) :  str(s) { }
32
33 // comparison
34 int mystring::compare_same_type(const basic &other) const
35 {
36         const mystring &o = static_cast<const mystring &>(other);
37         int cmpval = str.compare(o.str);
38         if (cmpval == 0)
39                 return 0;
40         else if (cmpval < 0)
41                 return -1;
42         else
43                 return 1;
44 }
45
46 // printing
47 void mystring::do_print(const print_context &c, unsigned level) const
48 {
49         // print_context::s is a reference to an ostream
50         c.s << '\"' << str << '\"';
51 }
52
53 /**
54  * evaluation: all strings automatically converted to lowercase with
55  * non-alphabetic characters stripped, and empty strings removed
56  */
57 ex mystring::eval(int level) const
58 {
59         string new_str;
60         for (size_t i=0; i<str.length(); i++) {
61                 char c = str[i];
62                 if (c >= 'A' && c <= 'Z') 
63                         new_str += tolower(c);
64                 else if (c >= 'a' && c <= 'z')
65                         new_str += c;
66         }
67
68         if (new_str.length() == 0)
69                 return 0;
70         else
71                 return mystring(new_str).hold();
72 }
73
74 int main(int argc, char** argv)
75 {
76         ex e = mystring("Hello, world!");
77         cout << is_a<mystring>(e) << endl;
78         cout << ex_to<basic>(e).class_name() << endl;
79         cout << e << endl;
80         ex another = pow(mystring("One string"), 2*sin(Pi-mystring("Another string")));
81         cout << another << endl;
82         return 0;
83 }