Determining Whether a Symbol is a Template Function - template-meta-programming

I'm trying to come up with a robust way of determining whether a given symbol is a function template. The following:
import std.traits: isSomeFunction;
auto ref identity(T)(auto ref T t) { return t; }
static assert(isSomeFunction!identity);
Will fail as identity is still a template until it is instantiated. Currently I am using a hack that relies on the fact that <template function symbol>.stringof is formatted a certain way:
//ex: f.stringof == identity(T)(auto ref T t)
template isTemplateFunction(alias f)
{
import std.algorithm: balancedParens, among;
enum isTemplateFunction = __traits(isTemplate, f)
&& f.stringof.balancedParens('(', ')')
&& f.stringof.count('(') == 2
&& f.stringof.count(')') == 2;
}
//Passes
static assert(isTemplateFunction!identity);
I'd like to know if there's a better way to do this other than hacky stringof parsing.

It seems there's no better way to do this in D as it is now, so I will stick to parsing .stringof, as dirty a hack as it is.

Related

Boost Ptree Custom Sort

I want to use this Function and make a custom sorting function, but I don't know how the Compare Function works or with a lambda.
Could someone be so kind to give me a working example for using it.
/* Sorts the direct children of this node according to the predicate.
The predicate is passed the whole pair of key and child. */
template <class Compare> void sort (Compare comp);
The predicate is passed the whole pair of key and child.
Is this a pair of key/ptree? I don't know how what the datatype is.
Im searching something like a lambda function equal for lists
unorderedGenList.sort([](const boost::property_tree::ptree & treeA, const boost::property_tree::ptree & treeB)
{
if(std::stod(treeA.get<std::string>("sortA","0")) < std::stod(treeB.get<std::string>("sortA","0"))
|| (std::stod(treeA.get<std::string>("sortA","0")) == std::stod(treeB.get<std::string>("sortA","0")) && std::stod(treeA.get<std::string>("sortB","0")) < std::stod(treeB.get<std::string>("sortB","0")))
)
return true;
return false;
});
I think i got the Solution
typedef std::pair< const Key, self_type > value_type;
unorderedPtree.sort([](const boost::property_tree::value_type& treeA, const boost::property_tree::value_type & treeB){
treeA.second.get<std::string>("sortB","0")) ...
}

How do I view the Ruby method #lcm in the source code?

I'm trying to understand how #lcm works. It belongs in the Integer class, as seen on the docs. I've looked at Ruby's github page but I don't know how to navigate it.
Thanks.
If you hover over a method in the Ruby docs you'll see "click to toggle source" on the right. Click on it and you'll see its definition:
VALUE
rb_lcm(VALUE self, VALUE other)
{
other = nurat_int_value(other);
return f_lcm(self, other);
}
This is C code, of course, rather than Ruby. Many of Ruby's core modules are implemented in C. For such modules I recommend another source of information: The Ruby Cross-Reference. There you can search for any C identifier, such as rb_lcm, and find its definition. In the case of Integer#lcm it's actually defined in rational.c (which you'll find in the root directory on GitHub). From there you can click on f_lcm to see its definition:
static VALUE
f_lcm(VALUE x, VALUE y)
{
if (f_zero_p(x) || f_zero_p(y))
return ZERO;
return f_abs(f_mul(f_div(x, f_gcd(x, y)), y));
}
...and so on.
Personally, I very much prefer to read Rubinius's source code over reading YARV's. Rubinius is much better structured, much better factored, and, above all, most of it is written in a language Ruby programmers know very well, namely Ruby:
def lcm(other)
raise TypeError, "Expected Integer but got #{other.class}" unless other.kind_of?(Integer)
if self.zero? or other.zero?
0
else
(self.div(self.gcd(other)) * other).abs
end
end
IronRuby's source code is also well structured, but unfortunately no longer really maintained:
[RubyMethod("lcm")]
public static object/*!*/ Lcm(int self, int other) {
return Lcm(self, other, SignedGcd(self, other));
}
[RubyMethod("lcm")]
public static object/*!*/ Lcm(BigInteger/*!*/ self, BigInteger/*!*/ other) {
return Lcm(self, other, SignedGcd(self, other));
}
[RubyMethod("lcm")]
public static object/*!*/ Lcm(object/*!*/ self, object other) {
throw RubyExceptions.CreateTypeError("not an integer");
}
My third choice would be JRuby:
public IRubyObject lcm(ThreadContext context, IRubyObject other) {
checkInteger(context, other);
return f_lcm(context, this, RubyRational.intValue(context, other));
}
Which points to this:
public static IRubyObject f_lcm(ThreadContext context, IRubyObject x, IRubyObject y) {
if (f_zero_p(context, x) || f_zero_p(context, y)) {
return RubyFixnum.zero(context.runtime);
}
return f_abs(context, f_mul(context, f_div(context, x, f_gcd(context, x, y)), y));
}

Benefit of defining success/failure function instead of using success/!success

I was reading man page of gearman code (http://manpages.ubuntu.com/manpages/precise/man3/gearman_success.3.html). They are having two functions
bool gearman_success(gearman_return_t rc)
bool gearman_failed(gearman_return_t rc)
And code of those functions look like (libgearman-1.0/return.h):
static inline bool gearman_failed(enum gearman_return_t rc)
{
return rc != GEARMAN_SUCCESS;
}
static inline bool gearman_success(enum gearman_return_t rc)
{
return rc == GEARMAN_SUCCESS;
}
Both function does nearly same thing. One return true and another false. What is the benefit of this code ?
Why not just have
!gearman_success
Is there benefit of coding pattern or something , which I am missing here.
This code is easier to extend. Suppose you add another value to that enum:
GEARMAN_SUCCESS_BUT_HAD_WARNINGS
With the implementation you're looking at, all you have to do is adjust both methods. Without it, you'd have to go through every place GEARMAN_SUCCESS is used all over the code base and make sure that the new enum value is handled properly.

How to replace lambda written in Where clause of Linq with equivalent delegate

I have an Query expression that uses a predicate type and lambda expression.
I am getting desired result with this. But I am not clear with how this expression is getting evaluated.
I tried to break this lambda expression by creating delegate and replacing condition under Where with delegate type.
If I have to rewrite the same thing with writing a delegate instead of anonymous type. What will be the syntax. How the delegate will be return for the same.
if (((DataTable)dgvAssignedRpm.DataSource).AsEnumerable()
.Where(row => row.Field<long>("FK_RPM_BTN_SETTING_ID") == objRpmButtonHolder.RpmSettingId).Count() > 1)
{
List<DataRow> listPkgBtnSettings = SearchForExistingSettingId();
}
void MethodSignature(...)
{
...
if (((DataTable)dgvAssignedRpm.DataSource).AsEnumerable()
.Where(RowCondition)
{
List<DataRow> listPkgBtnSettings = SearchForExistingSettingId();
}
...
}
// Where want a Func<T,bool> parameter
// T is the first parameter type (DataRow here)
// bool represents the return value
bool RowCondition(DataRow row)
{
return row.Field<long>("FK_RPM_BTN_SETTING_ID") == objRpmButtonHolder.RpmSettingId).Count() > 1
}
I assume the correct delegate replacement would be:
if (((DataTable)dgvAssignedRpm.DataSource).AsEnumerable().Where(
delegate(DataRow row) {
return (row.Field<long>("FK_RPM_BTN_SETTING_ID") == objRpmButtonHolder.RpmSettingId.Count() > 1);
}))
{
List<DataRow> listPkgBtnSettings = SearchForExistingSettingId();
}
But it's morning for me, so forgive me if I'm a bit off.
What the where desires is to give a DataRow as a parameter and a bool to return. You could just about fill in anything in the lambda or delegate, as long as it matches these requests.
To your question why it requests Func<> and how it works. The statement you're using is LINQ, so I found you a reference regarding this which can probably explain it better than me:
http://blogs.msdn.com/b/mirceat/archive/2008/03/13/linq-framework-design-guidelines.aspx
But yeah, the last type here in the Func<> is what it returns. (However, I can still recommend using the Lambda expression, as it's pretty clean, neat and serves the Func<> best.
(Also, look at what intellisence gives you when you write "new Func<....", it should give you a good idea of what Func wants and can do!)
Hope I was of help.

What are nested functions? What are they for?

I've never used nested functions, but have seen references to them in several languages (as well as nested classes, which I assume are related).
What is a nested function?
Why?!?
What can you do with a nested function that you cannot do any other way?
What can you do with a nested function this is difficult or inelegant without nested functions?
I assume nested functions are simply an artifact of treating everything as an object, and if objects can contain other objects then it follows.
Do nested functions have scope (in general, I suppose languages differ on this) just as variables inside a function have scope?
Please add the language you are referencing if you're not certain that your answer is language agnostic.
-Adam
One popular use of nested functions is closures. In a lexically scoped language with first-class functions it's possible to use functions to store data. A simple example in Scheme is a counter:
(define (make-counter)
(let ((count 0)) ; used to store the count
(define (counter) ; this is the counter we're creating
(set! count (+ count 1)) ; increment the count
count) ; return the new count
counter)) ; return the new counter function
(define mycounter (make-counter)) ; create a counter called mycounter
(mycounter) ; returns 1
(mycounter) ; returns 2
In this example, we nest the function counter inside the function make-counter, and by returning this internal function we are able to access the data available to counter when it was defined. This information is private to this instance of mycounter - if we were to create another counter, it would use a different spot to store the internal count. Continuing from the previous example:
(define mycounter2 (make-counter))
(mycounter2) ; returns 1
(mycounter) ; returns 3
It's useful for recursion when there is only 1 method that will ever call it
string[] GetFiles(string path)
{
void NestedGetFiles(string path, List<string> result)
{
result.AddRange( files in the current path);
foreach(string subPath in FoldersInTheCurrentPath)
NestedGetFiles(subPath, result);
}
List<string> result = new List<string>();
NestedGetFiles(path, result);
return result.ToArray();
}
The above code is completely made up but is based on C# to give the idea of what I mean. The only method that can call NestedGetFiles is the GetFiles method.
Nested functions allow you to encapsulate code that is only relevant to the inner workings of one function within that function, while still allowing you to separate that code out for readability or generalization. In some implementations, they also allow access to outer scope. In D:
int doStuff() {
int result;
void cleanUpReturn() {
myResource1.release();
myResource2.release();
return result * 2 + 1;
}
auto myResource1 = getSomeResource();
auto myResource2 = getSomeOtherResource();
if(someCondition) {
return cleanUpReturn();
} else {
doSomeOtherStuff();
return cleanUpReturn();
}
}
Of course, in this case this could also be handled with RAII, but it's just a simple example.
A nested function is simply a function defined within the body of another function. Why? About the only reason I could think of off the top of my head is a helper or utility function.
This is a contrived example but bear with me. Let's say you had a function that had to act on the results two queries and fill an object with values from one of the queries. You could do something like the following.
function process(qryResult q1, qryResult q2) {
object o;
if (q1.someprop == "useme") {
o.prop1 = q1.prop1;
o.prop2 = q1.prop2;
o.prop3 = q1.prop3;
} else if (q2.someprop == "useme") {
o.prop1 = q2.prop1;
o.prop2 = q2.prop2;
o.prop3 = q2.prop3;
}
return o;
}
If you had 20 properties, you're duplicating the code to set the object over and over leading to a huge function. You could add a simple nested function to do the copy of the properties from the query to the object. Like this:
function process(qryResult q1, qryResult q2) {
object o;
if (q1.someprop == "useme") {
fillObject(o,q1);
} else if (q2.someprop == "useme") {
fillObject(o,q2);
}
return o;
function fillObject(object o, qryResult q) {
o.prop1 = q.prop1;
o.prop2 = q.prop2;
o.prop3 = q.prop3;
}
}
It keeps things a little cleaner. Does it have to be a nested function? No, but you may want to do it this way if the process function is the only one that would have to do this copy.
(C#) :
I use that to simplify the Object Browser view, and to structure my classes better.
As class Wheel nested in Truck class.
Don't forget this detail :
"Nested types can access private and protected members of the containing type, including any inherited private or protected members."
They can also be useful if you need to pass a function to another function as an argument. They can also be useful for making factory functions for factory functions (in Python):
>>> def GetIntMaker(x):
... def GetInt():
... return x
... return GetInt
...
>>> GetInt = GetIntMaker(1)
>>> GetInt()
1
A nested function is just a function inside another function.
Yes, it is a result of everything being an object. Since you can have variables only visible in the function's scope and variables can point to functions you can have a function that is referenced by a local variable.
I don't think there is anything that you can do with a nested function that you absolutely couldn't do without. A lot of the times it makes sense, though. Namely, whenever a function is a "sub-function" of some other function.
A common use-case for me is when a function performs a lot of complicated logic but what the function computes/returns is easy to abstract for all the cases dictated by the logic.

Resources