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