Search Results

Search found 175 results on 7 pages for 'metaprogramming'.

Page 3/7 | < Previous Page | 1 2 3 4 5 6 7  | Next Page >

  • Traversing Scheme function as a list

    - by csl
    Isn't it possible to treat functions in Scheme as any other list? Basically, what I want do to is something like this: (define (foo) "hello") (cdr foo) ; or similar, should return the list ((foo) "hello") I've found a similar discussion about this, and I feel a bit disappointed if this is not possible with Scheme. If so, why is this impossible? Is it possible in other lisps? EDIT: Changed (cdr 'foo) to (cdr foo) -- it was misleading. I'm asking, why can't I access a function as a list?

    Read the article

  • Software tools for allowing end users to reprogram interfaces

    - by iceman
    What would be the examples of commercial software products (specially web-services) which allow the end user to reprogram their user-interface? I mean end users who do not know programming and they are allowed to add more functionality. One way of doing it is allowing XML gadgets like iGoogle does. What are the other approaches and also the technologies enabling them? This would be a futuristic application like collaborative software development for users.

    Read the article

  • Groovy Prototype Object

    - by Holden
    I have a method with an incoming variable, which represents a script. e.g. hello.groovy Foo.init(this) Foo.groovy class Foo { static init(app) { } } What is the best way to add a ton of new functionality to the app variable in the init method? Basically, I would like to add all the functionality of another object to the app object. For instance, if I had another class: class Bar { def a() { } def b() { } } I would like the app object to basically be a new Bar(). In JavaScript, this is easy by using the prototype object, but I cannot seem to get it working in groovy. What is the best way to accomplish this? Or should I be doing something differently?

    Read the article

  • Ruby metaclass madness

    - by t6d
    I'm stuck. I'm trying to dynamically define a class method and I can't wrap my head around the ruby metaclass model. Consider the following class: class Example def self.meta; (class << self; self; end); end def self.class_instance; self; end end Example.class_instance.class # => Class Example.meta.class # => Class Example.class_instance == Example # => true Example.class_instance == Example.meta # => false Obviously both methods return an instance of Class. But these two instances are not the same. They also have different ancestors: Example.meta.ancestors # => [Class, Module, Object, Kernel] Example.class_instance.ancestors # => [Example, Object, Kernel] Whats the point in making a difference between the metaclass and the class instance? I figured out, that I can send :define_method to the metaclass to dynamically define a method, but if I try to send it to the class instance it won't work. At least I could solve my problem, but I still want to understand why it is working this way.

    Read the article

  • Python: Class factory using user input as class names

    - by Sano98
    Hi everyone, I want to add class atttributes to a superclass dynamically. Furthermore, I want to create classes that inherit from this superclass dynamically, and the name of those subclasses should depend on user input. There is a superclass "Unit", to which I can add attributes at runtime. This already works. def add_attr (cls, name, value): setattr(cls, name, value) class Unit(object): pass class Archer(Unit): pass myArcher = Archer() add_attr(Unit, 'strength', 5) print "Strenght ofmyarcher: " + str(myArcher.strength) Archer.strength = 2 print "Strenght ofmyarcher: " + str(myArcher.strength) This leads to the desired output: Strenght ofmyarcher: 5 Strenght ofmyarcher: 2 But now I don't want to predefine the subclass Archer, but I'd rather let the user decide how to call this subclass. I've tried something like this: class Meta(type, subclassname): def __new__(cls, subclassname, bases, dct): return type.__new__(cls, subclassname, Unit, dct) factory = Meta() factory.__new__("Soldier") but no luck. I guess I haven't really understood what new does here. What I want as a result here is class Soldier(Unit): pass being created by the factory. And if I call the factory with the argument "Knight", I'd like a class Knight, subclass of Unit, to be created. Any ideas? Many thanks in advance! Bye -Sano

    Read the article

  • How to loop through a boost::mpl::list?

    - by Kyle
    This is as far as I've gotten, #include <boost/mpl/list.hpp> #include <algorithm> namespace mpl = boost::mpl; class RunAround {}; class HopUpAndDown {}; class Sleep {}; template<typename Instructions> int doThis(); template<> int doThis<RunAround>() { /* run run run.. */ return 3; } template<> int doThis<HopUpAndDown>() { /* hop hop hop.. */ return 2; } template<> int doThis<Sleep>() { /* zzz.. */ return -2; } int main() { typedef mpl::list<RunAround, HopUpAndDown, Sleep> acts; // std::for_each(mpl::begin<acts>::type, mpl::end<acts>::type, doThis<????>); return 0; }; How do I complete this? (I don't know if I should be using std::for_each, just a guess based on another answer here)

    Read the article

  • Generating tuples for tuples

    - by Nicola Bonelli
    Say you have a tuple and want to generate a new tuple by applying a metafunction on each type of the first one. What' the most efficient C++ metafuntion to accomplish to this task? Is it also possible to use C++0x variadic template to provide a better implementation?

    Read the article

  • Just introducing myself to TMPing, and came across a quirk

    - by Justen
    I was just trying to learn the syntax of the beginner things, and how it worked when I was making this short bit of code. The code below works in adding numbers 1 to 499, but if I add 1 to 500, the compiler bugs out giving me: fatal error C1001: An internal error has occurred in the compiler. And I was just wondering why that is. Is there some limit to how much code the compiler can generate or something and it just happened to be a nice round number of 500 for me? #include <iostream> using namespace std; template < int b > struct loop { enum { sum = loop< b - 1 >::sum + b }; }; template <> struct loop< 0 > { enum { sum = 0 }; }; int main() { cout << "Adding the numbers from 1 to 499 = " << loop< 499 >::sum << endl; return 0; }

    Read the article

  • About variadic templates

    - by chedi
    Hi, I'm currently experiencing with the new c++0x variadic templates, and it's quit fun, Although I have a question about the process of member instanciation. in this example, I'm trying to emulate the strongly typed enum with the possibility of choose a random valid strong enum (this is used for unit testing). #include<vector> #include<iostream> using namespace std; template<unsigned... values> struct sp_enum; /* this is the solution I found, declaring a globar var vector<unsigned> _data; and it work just fine */ template<> struct sp_enum<>{ static const unsigned _count = 0; static vector<unsigned> _data; }; vector<unsigned> sp_enum<>::_data; template<unsigned T, unsigned... values> struct sp_enum<T, values...> : private sp_enum<values...>{ static const unsigned _count = sp_enum<values...>::_count+1; static vector<unsigned> _data; sp_enum( ) : sp_enum<values...>(values...) {_data.push_back(T);} sp_enum(unsigned v ) {_data.push_back(v);} sp_enum(unsigned v, unsigned...) : sp_enum<values...>(values...) {_data.push_back(v);} }; template<unsigned T, unsigned... values> vector<unsigned> sp_enum<T, values...>::_data; int main(){ enum class t:unsigned{Default = 5, t1, t2}; sp_enum<t::Default, t::t1, t::t2> test; cout <<test._count << endl << test._data.size() << endl; for(auto i= test._data.rbegin();i != test._data.rend();++i){cout<< *i<< ":";} } the result I'm getting with this code is : 3 1 5: can someone point me what I'm messing here ??? Ps: using gcc 4.4.3

    Read the article

  • Accessing a class's containing namespace from within a module

    - by SFEley
    I'm working on a module that, among other things, will add some generic 'finder' type functionality to the class you mix it into. The problem: for reasons of convenience and aesthetics, I want to include some functionality outside the class, in the same scope as the class itself. For example: class User include MyMagicMixin end # Should automagically enable: User.name('Bob') # Returns first user named Bob Users.name('Bob') # Returns ALL users named Bob User(5) # Returns the user with an ID of 5 Users # Returns all users I can do the functionality within these methods, no problem. And case 1 (User.name('Bob')) is easy. Cases 2–4, however, require being able to create new classes and methods outside User. The Module.included method gives me access to the class, but not to its containing scope. There is no simple "parent" type method that I can see on Class nor Module. (For namespace, I mean, not superclass nor nested modules.) The best way I can think to do this is with some string parsing on the class's #name to break out its namespace, and then turn the string back into a constant. But that seems clumsy, and given that this is Ruby, I feel like there should be a more elegant way. Does anyone have ideas? Or am I just being too clever for my own good?

    Read the article

  • Dynamic/runtime method creation (code generation) in Python

    - by Eli Bendersky
    Hello, I need to generate code for a method at runtime. It's important to be able to run arbitrary code and have a docstring. I came up with a solution combining exec and setattr, here's a dummy example: class Viking(object): def __init__(self): code = ''' def dynamo(self, arg): """ dynamo's a dynamic method! """ self.weight += 1 return arg * self.weight ''' self.weight = 50 d = {} exec code.strip() in d setattr(self.__class__, 'dynamo', d['dynamo']) if __name__ == "__main__": v = Viking() print v.dynamo(10) print v.dynamo(10) print v.dynamo.__doc__ Is there a better / safer / more idiomatic way of achieving the same result?

    Read the article

  • Compile time string hashing

    - by Caspin
    I have read in few different places that using c++0x's new string literals it might be possible to compute a string's hash at compile time. However, no one seems to be ready to come out and say that it will be possible or how it would be done. Is this possible? What would the operator look like? I'm particularly interested use cases like this. void foo( const std::string& value ) { switch( std::hash(value) ) { case "one"_hash: one(); break; case "two"_hash: two(); break; /*many more cases*/ default: other(); break; } } Note: the compile time hash function doesn't have to look exactly as I've written it. I did my best to guess what the final solution would look like, but meta_hash<"string"_meta>::value could also be a viable solution.

    Read the article

  • What is Ruby's analog to Python Metaclasses?

    - by Sean Copenhaver
    Python has the idea of metaclasses that, if I understand correctly, allow you to modify an object of a class at the moment of construction. You are not modifying the class, but instead the object that is to be created then initialized. Python (at least as of 3.0 I believe) also has the idea of class decorators. Again if I understand correctly, class decorators allow the modifying of the class definition at the moment it is being declared. Now I believe there is an equivalent feature or features to the class decorator in Ruby, but I'm currently unaware of something equivalent to metaclasses. I'm sure you can easily pump any Ruby object through some functions and do what you will to it, but is there a feature in the language that sets that up like metaclasses do? So again, Does Ruby have something similar to Python's metaclasses? Edit I was off on the metaclasses for Python. A metaclass and a class decorator do very similar things it appears. They both modify the class when it is defined but in different manners. Hopefully a Python guru will come in and explain better on these features in Python. But a class or the parent of a class can implement a __new__(cls[,..]) function that does customize the construction of the object before it is initialized with __init__(self[,..]).

    Read the article

  • How does this ruby custom accessor work

    - by ennuikiller
    So the method below in class_eval dynamically creates accessors for attributes defined at runtime. It can be used, for example, to create configuration objects with attributes read from a config file (and unknown until runtime). I understanding all of it except for the else branch. If I am correct the else branch returns the attribute value (val[0]) if there is one value passed in *val. However the way its written I would expect it to return an array (val) if there is more then one value passed in *var. In particular, if I have something like the following: value = 5 then from reading the code I would expect "#{@value}" to be [=,5]. However "#{@value}" returns 5 and not the array [=,5]. How is this possible? class Module def dsl_accessor(*symbols) symbols.each do |sym| class_eval %{ def #{sym}(*val) if val.empty? @#{sym} else @#{sym} = val.size == 1 ? val[0] : val end end } end end end

    Read the article

  • Generating tuples from tuples

    - by Nicola Bonelli
    Say you have a tuple and want to generate a new tuple by applying a metafunction on each type of the first one. What' the most efficient C++ metafuntion to accomplish to this task? Is it also possible to use C++0x variadic template to provide a better implementation?

    Read the article

  • How Does Ctrl-K work in Stackoverflow

    - by harigm
    I am very curious to know how to implement the Ctrl-K feature against code, For sample public static void main(Stirng args[]){ System.out.println.out("welcome"); } That will be nicely formatted? 1)Do we require any package to implement this? 2) Any ready made code avaialble to do this? Can any one help me with this, I am planning to develop a site where this feature would be a real helpful.

    Read the article

  • Are C++ meta-templates required knowledge for programmers?

    - by Robert Gould
    In my experience Meta-templates are really fun (when your compilers are compliant), and can give good performance boosts, and luckily I'm surrounded by seasoned C++ programmers that also grok meta-templates, however occasionally a new developer arrives and can't make heads or tails of some of the meta-template tricks we use (mostly Andrei Alenxandrescu stuff), for a few weeks until he gets initiated appropriately. So I was wondering what's the situation for other C++ programmers out there? Should meta-template programming be something C++ programmers should be "required" to know (excluding entry level students of course), or not? Edit: Note my question is related to production code and not little samples or prototypes

    Read the article

  • How can I use functools.partial on multiple methods on an object, and freeze parameters out of order

    - by Joseph Garvin
    I find functools.partial to be extremely useful, but I would like to be able to freeze arguments out of order (the argument you want to freeze is not always the first one) and I'd like to be able to apply it to several methods on a class at once, to make a proxy object that has the same methods as the underlying object except with some of its methods parameter being frozen (think of it as generalizing partial to apply to classes). I've managed to scrap together a version of functools.partial called 'bind' that lets me specify parameters out of order by passing them by keyword argument. That part works: >>> def foo(x, y): ... print x, y ... >>> bar = bind(foo, y=3) >>> bar(2) 2 3 But my proxy class does not work, and I'm not sure why: >>> class Foo(object): ... def bar(self, x, y): ... print x, y ... >>> a = Foo() >>> b = PureProxy(a, bar=bind(Foo.bar, y=3)) >>> b.bar(2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: bar() takes exactly 3 arguments (2 given) I'm probably doing this all sorts of wrong because I'm just going by what I've pieced together from random documentation, blogs, and running dir() on all the pieces. Suggestions both on how to make this work and better ways to implement it would be appreciated ;) One detail I'm unsure about is how this should all interact with descriptors. Code follows. from types import MethodType class PureProxy(object): def __init__(self, underlying, **substitutions): self.underlying = underlying for name in substitutions: subst_attr = substitutions[name] if hasattr(subst_attr, "underlying"): setattr(self, name, MethodType(subst_attr, self, PureProxy)) def __getattribute__(self, name): return getattr(object.__getattribute__(self, "underlying"), name) def bind(f, *args, **kwargs): """ Lets you freeze arguments of a function be certain values. Unlike functools.partial, you can freeze arguments by name, which has the bonus of letting you freeze them out of order. args will be treated just like partial, but kwargs will properly take into account if you are specifying a regular argument by name. """ argspec = inspect.getargspec(f) argdict = copy(kwargs) if hasattr(f, "im_func"): f = f.im_func args_idx = 0 for arg in argspec.args: if args_idx >= len(args): break argdict[arg] = args[args_idx] args_idx += 1 num_plugged = args_idx def new_func(*inner_args, **inner_kwargs): args_idx = 0 for arg in argspec.args[num_plugged:]: if arg in argdict: continue if args_idx >= len(inner_args): # We can't raise an error here because some remaining arguments # may have been passed in by keyword. break argdict[arg] = inner_args[args_idx] args_idx += 1 f(**dict(argdict, **inner_kwargs)) new_func.underlying = f return new_func

    Read the article

  • How do I fix this NameError?

    - by Kyle Kaitan
    I want to use the value v inside of an instance method on the metaclass of a particular object: v = ParserMap[kind][:validation] # We want to use this value later. s = ParserMap[kind][:specs] const_set(name, lambda { p = Parser.new(&s) # This line starts a new scope... class << p define_method :validate do |opts| v.call(self, opts) # => NameError! The `class` keyword above # has started a new scope and we lost # old `v`. end end p }) Unfortunately, the class keyword starts a new scope, so I lose the old scope and I get a NameError. How do I fix this?

    Read the article

  • Is it possible to replace groovy method for existing object?

    - by Jean Barmash
    The following code tried to replace an existing method in a Groovy class: class A { void abc() { println "original" } } x= new A() x.abc() A.metaClass.abc={-> println "new" } x.abc() A.metaClass.methods.findAll{it.name=="abc"}.each { println "Method $it"} new A().abc() And it results in the following output: original original Method org.codehaus.groovy.runtime.metaclass.ClosureMetaMethod@103074e[name: abc params: [] returns: class java.lang.Object owner: class A] Method public void A.abc() new Does this mean that when modify the metaclass by setting it to closure, it doesn't really replace it but just adds another method it can call, thus resulting in metaclass having two methods? Is it possible to truly replace the method so the second line of output prints "new"? When trying to figure it out, I found that DelegatingMetaClass might help - is that the most Groovy way to do this?

    Read the article

  • Tutorials and Introductions to C++ Expression Templates

    - by grrussel
    What are good introductions to the creation of C++ expression template systems? I would like to express arithmetic on user defined types while avoiding temporary values (which may be large), and to learn how to do this directly rather than applying an existing library. I have found Todd Veldhuizen's original paper and an example from the Josuttis C++ Templates book, and an article by Kreft & Langer. I am looking for simple, clear expositions.

    Read the article

  • Define Instance Variable Outside of Method Defenition (ruby)

    - by Ell
    Hi all, I am developing (well, trying to at least) a Game framework for the Ruby Gosu library. I have made a basic event system wherebye each Blocks::Event has a list of handlers and when the event is fired the methods are called. At the moment the way to implement an event is as follows: class TestClass attr_accessor :on_close def initialize @on_close = Blocks::Event.new end def close @on_close.fire(self, Blocks::OnCloseArgs.new) end end But this method of implementing events seems rather long, my question is, how can I make a way so that when one wants an event in a class, they can just do this class TestClass event :on_close def close @on_close.fire(self, Blocks::OnCloseArgs.new) end end Thanks in advance, ell.

    Read the article

  • Re-Include Module

    - by Nino55
    Hello, I need some like this: module One def test; puts 'Test One'; end end module Two def test; puts 'Test Two'; end end class Foo include One include Two include One end In this case I need as a result 'Test One' but obviously it returns 'Test Two'. I need a clean simple way for re-include my module. Any suggestion? Thanks!

    Read the article

  • How to retrieve caller context object in Ruby ?

    - by David
    Hi, hereafter is my piece of code that I want to simplify in order to avoid passing an extra argument on each call : module M def do_something(context) puts "Called from #{context}" end module_function :do_something end class Foo def do_stuff M.do_something(self) end end Foo.new.do_stuff Is there a way to do the same think without passing 'self' as an input argument to 'do_something' method like this ? module M def do_something puts "Called from #{method that returns caller object}" end module_function :do_something end class Foo def do_stuff M.do_something end end Foo.new.do_stuff Thanks for your support!

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >