2 * @file mystring.cpp Example of extending GiNaC: writing new classes
9 #include <ginac/ginac.h>
10 using namespace GiNaC;
12 class mystring : public basic
14 GINAC_DECLARE_REGISTERED_CLASS(mystring, basic)
16 mystring(const string &s);
17 mystring(const char *s);
18 ex eval(int level) const;
24 void do_print(const print_context &c, unsigned level = 0) const;
28 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(mystring, basic,
29 print_func<print_context>(&mystring::do_print))
32 mystring::mystring() : inherited(&mystring::tinfo_static) { }
33 mystring::mystring(const string &s) : inherited(&mystring::tinfo_static), str(s) { }
34 mystring::mystring(const char *s) : inherited(&mystring::tinfo_static), str(s) { }
37 int mystring::compare_same_type(const basic &other) const
39 const mystring &o = static_cast<const mystring &>(other);
40 int cmpval = str.compare(o.str);
49 // archiving/unarchiving
50 mystring::mystring(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
52 n.find_string("string", str);
55 void mystring::archive(archive_node &n) const
57 inherited::archive(n);
58 n.add_string("string", str);
61 ex mystring::unarchive(const archive_node &n, lst &sym_lst)
63 return (new mystring(n, sym_lst))->setflag(status_flags::dynallocated);
67 void mystring::do_print(const print_context &c, unsigned level) const
69 // print_context::s is a reference to an ostream
70 c.s << '\"' << str << '\"';
74 * evaluation: all strings automatically converted to lowercase with
75 * non-alphabetic characters stripped, and empty strings removed
77 ex mystring::eval(int level) const
80 for (size_t i=0; i<str.length(); i++) {
82 if (c >= 'A' && c <= 'Z')
83 new_str += tolower(c);
84 else if (c >= 'a' && c <= 'z')
88 if (new_str.length() == 0)
91 return mystring(new_str).hold();
94 int main(int argc, char** argv)
96 ex e = mystring("Hello, world!");
97 cout << is_a<mystring>(e) << endl;
98 cout << ex_to<basic>(e).class_name() << endl;
100 ex another = pow(mystring("One string"), 2*sin(Pi-mystring("Another string")));
101 cout << another << endl;