How to Add Builtin Functions

Add a method to a Built-In Function

The fully general answer is that you can't. The built-in stuff is implemented at a lower level than normal classes, so you get a little less freedom for monkey-patching and such.

Depending on what specifically you're after, there can be workarounds though. For example, if you want a list with some extra methods, you can just subclass it

How to add a user-defined function as a built-in function in Perl?

If you want to emulate a built-in, then you don't need a class, you just need a library. Libraries are also implemented as packages in Perl, but the subroutines in them don't expect to have a classname or object passed as their first parameter. You can also use Exporter to insert your subroutines into the calling program's symbol table.

It would look something like this:

package Array::Printer;

use strict;
use warnings;
use feature 'say';

require Exporter;
our @ISA = qw[Exporter];
our @EXPORT = qw[println];

sub println {
say for @_;
}

1;

And you would use it like this:

#!/usr/bin/perl

use strict;
use warnings;

use lib '.';
use Array::Printer;

# I've used @stack instead of @_ in my code as @_ is a
# special variable and it seems strange to use it in another way.

my @stack = (1, 8, 14, 45);
push(@stack, 69);
push(@stack, 55);
push(@stack, 65536);
push(@stack, 4294967296);

println(@stack);

pop(@stack);
pop(@stack);
pop(@stack);

println(@stack);

Update: Notice that my library module is called Array::Printer. Your original class should have used the same name. Generally, Perl package names (both libraries and classes) should match the name of the file they are stored in. You called your package Printer but you used Array::Printer. This is guaranteed to confuse any maintenance programmer (even you!)

The use lib '.' in my code adds the current directory to the list of directories that Perl searches for libraries and classes. So we're assuming that the code for Array::Printer is in a file called Printer.pm in a directory called Array in your current directory (which is also, presumably, where your main program is. A double-colon in a Perl library name (::) is translated to a directory separator (/) when looking for the file that contains the library.

How to define built in function in my python interpreter?

Use Customisation Modules: https://docs.python.org/3/tutorial/appendix.html#the-customization-modules

With it, you can run code and define methods that are available when Python starts up interactively.

First, find where Python is looking for the user customisation directory is. Start python and type:

>>> import site
>>> site.getusersitepackages()
'/home/user/myuser/.local/lib/python3.5/site-packages'

The last string given is the customisation directory. If it does not exist, create it. Then create a file in your customisation directory called usercustomize.py. Add your code from the question to it. Save and restart Python.

Voila! You can now type:

>>> clear()

python adding new methods to built-in types

Strings are objects and thus have methods. lower() is one of them.

You cannot add a custom method to str, unicode or any other builtin (written in C) classes - see Implementing a custom string method and Extending builtin classes in python

How to use compiler builtin functions without Standard C library

Lets say you wanted to replace the function cos, all you have to do is replace every occurance of cos in your code with __builtin_cos. The same goes for any other function that you can replace with the compiler's version. Just prepend __builtin_ to the name.

For more information consult the gcc manual.

Dynamically adding builtin methods to point to a property's built-ins

The main problem to get around is that magic methods like __add__ are looked up on the class, not on the object itself; otherwise you could just write self.__add__ = a.__add__ in the __init__ method. To get around this, we need to declare methods on the class B, not on individual instances of it.

The function delegate defined below works by adding a method to the B class. This method takes self which will be a B instance, so it has to dynamically load the a attribute and then its __add__ method.

class A:
def __add__(self, other):
return 9
def __mul__(self, other):
return 7
def __sub__(self, other):
return 8

class B:
def __init__(self, a):
self.a = a

def delegate(cls, attr_name, method_name):
def delegated(self, *vargs, **kwargs):
a = getattr(self, attr_name)
m = getattr(a, method_name)
return m(*vargs, **kwargs)
setattr(cls, method_name, delegated)

delegate(B, 'a', '__add__')
delegate(B, 'a', '__sub__')

Example:

>>> b = B(A())
>>> b + 3
9
>>> b - 4
8

How to add member function for built-in types such as integer in C++

You could do as cornstalks suggests and use the same technique employed by std::begin and std::end. It provides overloads for objects that define begin/end member functions and provides overloads for further types (in that case arrays) which it makes sense to use the function on.

In the below contrived example, we have a getval free function, which provides overloads for types that define a getval member function, using the trailing return type to activate SFINAE. Then for other types it uses type traits to ensure that only types which are integers are allowed and all others rejected, again using SFINAE via enable_if.

This example is contrived and is only intended to show the technique, which you can employ to implement whichever functionality you require (the question does not elaborate what that is, so I had to use license). It would clearly be easier in the below case to achieve the same effect by adding an int conversion operator to the IndexB_t class, but that's not the point.

#include <iostream>
#include <type_traits>
using namespace std;

/* is_integer type trait */
template<typename T>
using is_integer = is_same<remove_cv_t<T>, int>;

template<typename T>
constexpr bool is_integer_v = is_integer<T>::value;

/* getval function definition */
template<typename T,
typename = enable_if_t<is_integer_v<T>>
>
T getval(T i)
{ return i; }

template<typename T>
auto getval(T& t) -> decltype(t.getval())
{ return t.getval(); }

/* defined types */
typedef int IndexA_t;

class IndexB_t
{
int x;

public:
IndexB_t(int i) : x(i) {}

int getval() const { return x; }
};

// a test struct with no `getval` member function.
struct NoGetVal {};

// driver function
int main()
{
int i = 9;
IndexB_t j = 10;
IndexA_t k = 11;
const int l = 12;
volatile int m = 13;
const volatile int n = 14;
float a = 1.1;
NoGetVal ngv;

cout << getval(i) << '\n';
cout << getval(j) << '\n';
cout << getval(k) << '\n';
cout << getval(l) << '\n';
cout << getval(m) << '\n';
cout << getval(n) << '\n';

// disallowed as not int
//cout << getval(a) << '\n';

// disallowed no `getval` member function
//cout << getval(ngv) << '\n';
}

So now you have a consistent interface for integer primitives and objects that act like integers.

You may want to lessen the restriction on which types are allowed in the primitive type overload, perhaps using std::is_integral. It's up to you.

This is c++14 but could be stepped down to c++11 by using enable_if instead of enable_if_t et al. and adapting the code accordingly.



Related Topics



Leave a reply



Submit