I want to have a vector that has a number of independent variables. In my C++ header(.h) I defined it like this:
private:
// Static data structure holding independent variables
static vector<double>* indVariables;
And in my .cpp file it is defined the same and then I'm going to have to use this vector in some other function like this:
static vector<double>* indVariables;
void fun(int m, int n)
{
for (i = 0; i < m; ++i)
{
ai = indVariables[i];
temp = exp(-n * (ai - 8.0));
}
} /* fun */
Now in C# I want to copy a set of numbers to this vector and call it back to C++ something like this:
var matu = new double[]{ 8.0, 8.0, 10.0, 10.0, 10.0, 10.0};
myCppClass.indVariables = matu;
How can I do it?
The first problem is because it is private I don't see it in C#. Do I have to make it public or are there other ways? And then how can I assign values to this vector?
The fact that it is private does present an issue, but, making it public won't just solve your problem I think. C# doesn't know what an std::vector is, as Richard said. I don't know much about the structure of your code, what its doing, how its being used, etc, but, if all you need is to assign a list/array of numbers to the vector, you could use a List<> in your C# code and wrap the assignment of the vector in something like this in your CLI project/file:
void Assign(Collections::Generic::List<double>^ l )
{
IndVariables->clear();
for each (double i in l)
{
IndVariables->push_back(i);
}
}
Then in your C# program, you'd write (or however you've declared your List<>):
yourCppClass.Assign(new List<double>(){0.0, 42.0, 8.0});
You could also add additional wrapper methods to manipulate or access the vector. Again, this may or may not be suitable depending on the structure of your code.
Quoting the Collections documentation for C++/CX:
In a Visual C++ component extensions (C++/CX) program, you can make
free use of Standard Template Library (STL) containers, or any other
user-defined collection type. However, when you pass collections back
and forth across the Windows Runtime application binary interface
(ABI)—for example, to a XAML control or to a JavaScript client—you
must use Windows Runtime collection types.
So, you can use STL containers as much as you like internally, but you won't be able to pass them between runtime components as they don't cross ABI boundaries.
A quick fix would be to use the Vector class available at the Platform::Collections namespace through <collection.h>.
Change your header declaration to:
public:
static Vector<Double>^ IndVariables;
Your C# component needs to change as well:
var matu = new Double[] { 8.0, 8.0, 10.0, 10.0, 10.0, 10.0};
myCppClass.IndVariables = matu;
This is untested code, so syntax errors or other minor issues should be present in the snippets above.
In C++ templates have the feature that you can pass a value as the argument to the template of a function. How can I do the same in C#?
For instance, I want to do something similar to the following:
template <unsigned n> struct Factorial {
enum {
result = n * Factorial<n - 1>::result;
};
};
template <> struct Factorial<0> {
enum {
result = 1;
};
};
but in C#. How can I do this?
By the way, my actual need for them involves generating classes on demand (with a few static values changed), so the presented code is just an example.
C# generics are not like C++ templates in that way. They only work with types and not values.
but in C#. How can I do this?
By the way, my actual need for them involves generating classes on demand (with a few static values changed), so the presented code is just an example.
As Daniel explained, this is not possible via generics.
One potential alternative is to use T4 Templates. Depending on your needs, you could potentially generate your classes based off the templates at compile time, which sounds like it might meet your needs.
You are trying to make the compiler do stuff that your code should do at runtime.
Yes, this is possible in C++. In C#, It is not. The equivalent of your code in C# would be:
public class Factorial
{
public static ulong Compute(ulong n)
{
if (n == 0)
return 1;
return n * Factorial.Compute(n - 1);
}
}
Note that, while static code is already a bad violation of the OOP principle (but sometimes necessary), using value-based templates is even worse. Your types should depend on other types, which is possible using generics. They should not depend on concrete values.
Introduction
As a developer, I'm involved in writing a lot of mathematical code everyday and I'd like to add very few syntactic sugar to the C# language to ease code writing and reviewing.
I've already read about this thread and this other one for possible solutions and would simply like to know which best direction to go and how much effort it may represent to solve only for the three following syntactical issues*.
*: I can survive without described syntactic sugars, but if it ain't too much work and Rube-Goldberg design for simple compilation process, it may be interesting to investigate further.
1. Multiple output arguments
I'd like to write:
[double x, int i] = foo(z);
Instead of:
double x;
int i;
foo(out x, out i, z);
NB: out parameters being placed first and foo being declared as usual (or using same kind of syntax).
2. Additional operators
I'd like to have a few new unary/binary operators. Don't know much how to define for these (and it seems quite complex for not introducing ambiguity when parsing sources), anyway would like to have something like:
namespace Foo
{
using binary operator "\" as "MyMath.LeftDivide";
using unary operator "'" as "MyMath.ConjugateTranspose";
public class Test
{
public void Example()
{
var y = x';
var z = x \ y;
}
}
}
Instead of:
namespace Foo
{
public class Test
{
public void Example()
{
var y = MyMath.ConjugateTranspose(x);
var z = MyMath.LeftDivide(x, y);
}
}
}
3. Automatic name insertion for static classes
It's extremely unappealing to endlessly repeating Math.BlaBlaBla() everywhere in a computation code instead of writing directly and simply BlaBlaBla.
For sure this can be solved by adding local methods to wrap Math.BlaBlaBla inside computation class. Anyway would be better when there's no ambiguity at all, or when ambiguity would be solved with some sort of implicit keyword, to automatically insert class names when required.
For instance:
using System;
using implicit MySystem; // Definying for 'MyMaths.Math.Bessel'
public class Example
{
public Foo()
{
var y = 3.0 * Cos(12.0);
var z = 3.0 * Bessel(42);
}
// Local definition of 'Bessel' function again
public static double Bessel(double x)
{
...
}
}
Would become:
using System;
using MySystem; // Definying for 'Math.Bessel'
public class Example
{
public Foo()
{
var y = 3.0 * System.Math.Cos(12.0); // No ambiguity at all
var z = 3.0 * MySystem.Math.Bessel(42); // Solved from `implicit` keyword
}
// Local definition of 'Bessel' function again
public static double Bessel(double x)
{
...
}
}
* The compiler may simply generate a warning to indicate that it solved the ambiguity because an implicit solution has been defined.
NB: 3) is satisfying enough for solving 2).
Have you considered using F# instead of C#? In my experience, I have found F# a great fit for scientific/mathematical oriented code, more so than C#.
Your first scenario is covered with tuples; you can write a function like let f a b = (a+b, a-b), which returns a tuple of 2 values directly, you can fairly easily overload operators or add your own, and modules may help you with the 3rd. And F# interoperates fairly smoothly with C#, so you can even pick F# for the parts where it's practical, and keep the rest of your code in C#. There are other niceties which work great for scientific code (units of measure for instance) as well...
I'd be one of the first people to support a mainstream C# that can be extended by users. However - for several reasons (design, time or cost-benefit) I cannot see C# being as extensible as you (or I) want. A C#-derived language I've found that is VERY good for meta-programming and extending functionality/syntax is Nemerle.
Boo is another .NET language with good meta-programming features. However, it is so far removed from C# that I didn't consider it an appropriate answer to this question (but added it for completeness, anyway).
I am translating a program written in C++ to C#, and I have come across an intrinsic function that I cannot work around. In C++ this is known as:
unsigned char _BitScanForward(unsigned long * Index, unsigned long Mask);
If I only knew what DLL, if any, the intrinsic functions were in, I could use P/Invoke. Since I do not know, I looked for alternatives in the .NET framework, but I have come up empty handed.
Does anyone know how use P/Invoke on _BitScanForward, or an .NET method that does the same thing?
Any help is appreciated, thank you.
Intrinsic functions aren't in any library, they're implemented inside the CPU, the compiler emits the machine code which the CPU recognizes as evoking this particular behavior.
They're a way of getting access to instructions that don't have a simple C equivalent.
Until the .NET optimizer becomes smart enough to recognize them (for example, the Mono JIT recognizes some SIMD instructions, encoded in MSIL as calls to functions of a particular class, similarly the .NET JIT replaces calls to System.Math methods with floating-point operations), your C# code is doomed to run an order of magnitude slower than the original C++.
The _BitScanForward C++ function is an intrinsic compiler function. It finds the first on bit in a sequence of bytes searching from the lowest order bit to the highest and returning the value of the bit. You could probably implement something similar using bit manipulation tactics in C# (though it'll never come close to the same performance). If you're comfortable with bit manipulation in C++ then its basically the same in C#.
_BitScanForward searches for the first set bit in an integer, starting from the least significant bit searching towards the most significant bit. It compiles to the bsf instruction on the x86 platform.
The bit twiddling hacks page includes a handful of potential replacement algorithms that excel in different situations. There's an O(N) function (that half the time with uniformly-distributed inputs returns with only one iteration) and some sub-linear options, and some that make use of multiplication steps. Picking one might not be trivial, but any should work.
Wow, looks like there is a question on C# that haven't yet been covered with the recent improvements.
Other commenters have properly noted that the intrinsics like _BitScanForward are not functions per se, those are rather markers for the compiler to inject a specific platform instruction into the object code. It is impossible to emulate an intrinsic in a high-level language (unless you're willing to pay an abstraction penalty).
However, good news is that starting with .Net Core 3.0 the JIT does support the intrinsics for a number of hardware platforms.
For the _BitScanForward you might use System.Runtime.Intrinsics.X86.Bmi1.TrailingZeroCount.
Caveat: Don't forget to check for Bmi1.IsSupported before using, otherwise the code would fail at runtime.
You could also get a decent execution speed on ARM (.Net 5.0+) by using their ffs intrinsics:
public int ArmBitScanForward(int x)
=> 32 − System.Runtime.Intrinsics.Arm.ArmBase.LeadingZeroCount(x & −x);
public int ArmBitScanForward(long x)
=> 64 − System.Runtime.Intrinsics.Arm.ArmBase.Arm64.LeadingZeroCount(x & −x);
If neither platform is present, you would have to resort to the bit-twiddling hacks like de-Bruijun sequences:
for i from 0 to 31: table[ ( 0x077CB531 * ( 1 << i ) ) >> 27 ] ← i // table [0..31] initialized
function ctz5 (x)
return table[((x & -x) * 0x077CB531) >> 27]
(taken from https://en.wikipedia.org/wiki/Find_first_set)
Depending on the task restrictions, I would choose across different strategies of the algorithm selection at runtime. Branching on each call is likely to kill all the efficiency. The most efficient way is to branch on a level higher - i.e. have three versions of your code to choose from at run time.
An easy way to automate codegen is to have your code in a generic from parameterized with a bit-handling type:
public interface IBitScanner
{
int BitScanForward(int x);
}
public int MyFunction<T>(int[] data)
where T: new, IBitScanner
{
var s=0;
var scanner = new T();
foreach(var i in data)
s+= scanner.BitScanForward(i);
return s;
}
Then we define a couple of structs implementing our scanner:
public struct BitScannerX86: IBitScanner
{
public int BitScanForward(int x)
=> unchecked((int)System.Runtime.Intrinsics.X86.Bmi1.TrailingZeroCount((uint)x));
}
public struct BitScannerArm: IBitScanner
{
public int BitScanForward(int x)
=> 32 − System.Runtime.Intrinsics.Arm.ArmBase.LeadingZeroCount(x & −x);
}
public struct BitScanner: IBitScanner
{
private static int[] _table = InitTable();
private static int[] InitTable()
{
var table = new int[32];
for(var i=0; i<table.Length; i++)
table[i] = ( 0x077CB531 * ( 1 << i ) ) >> 27;
return table;
}
public int BitScanForward(int x)
=> _table[((x & -x) * 0x077CB531) >> 27]
}
Now whenever we need a platform-specific version of MyFunction, we do it via
MyFunction<BitScannerArm>. Being struct, the type parameter forces JIT to generate the specific code for it instead of a generic one fancying a virtual call.
Then, as the T is known at JIT time, the call to BitScanForward gets inlined, and ends up with the appropriate intrinsic injected into the loop.
Depending on the MyFunction task size, this version of MyFunction might be saved to a delegate, be part of an interface, or be part of a struct that implements an interface to repeat the trick one level higher.
Note that original question didn't bother with the cross-platform compatibility, as the _BitScanForward is an Intel-only instruction.
It was probably Ok in the C++ world of compiling an executable against a specific OS&HW combination; contemporary managed code like Java/.Net has a chance to be executed anywhere.
It is not possible to P/Invoke _BitScanForward because it is a compiler intrinsic, not an actual library function (it gets translated by the Visual C++ compiler to a BSF x86 machine instruction). As far as I'm aware, there is no MSIL instruction for this "find first set" operation. The simplest thing to do is write your own C++ native DLL that exports a function that invokes _BitScanForward(), and then P/Invoke that.
You can also write it directly in C# using bit manipulation (see Algorithms for find first set in Wikipedia). I'm not sure if this would be faster or slower than P/Invoke. Measure and find out.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have seen samples of closure from - What is a 'Closure'?
Can anyone provide simple example of when to use closure?
Specifically, scenarios in which closure makes sense?
Lets assume that the language doesn't have closure support, how would one still achieve similar thing?
Not to offend anyone, please post code samples in a language like c#, python, javascript, ruby etc. I am sorry, I do not understand functional languages yet.
Closures are simply great tools. When to use them? Any time you like... As has already been said, the alternative is to write a class; for example, pre C# 2.0, creating a parameterised thread was a real struggle. With C# 2.0 you don't even need the `ParameterizedThreadStart' you just do:
string name = // blah
int value = // blah
new Thread((ThreadStart)delegate { DoWork(name, value);}); // or inline if short
Compare that to creating a class with a name and value
Or likewise with searching for a list (using a lambda this time):
Person person = list.Find(x=>x.Age > minAge && x.Region == region);
Again - the alternative would be to write a class with two properties and a method:
internal sealed class PersonFinder
{
public PersonFinder(int minAge, string region)
{
this.minAge = minAge;
this.region = region;
}
private readonly int minAge;
private readonly string region;
public bool IsMatch(Person person)
{
return person.Age > minAge && person.Region == region;
}
}
...
Person person = list.Find(new PersonFinder(minAge,region).IsMatch);
This is fairly comparable to how the compiler does it under the bonnet (actually, it uses public read/write fields, not private readonly).
The biggest caveat with C# captures is to watch the scope; for example:
for(int i = 0 ; i < 10 ; i++) {
ThreadPool.QueueUserWorkItem(delegate
{
Console.WriteLine(i);
});
}
This might not print what you expect, since the variable i is used for each. You could see any combination of repeats - even 10 10's. You need to carefully scope captured variables in C#:
for(int i = 0 ; i < 10 ; i++) {
int j = i;
ThreadPool.QueueUserWorkItem(delegate
{
Console.WriteLine(j);
});
}
Here each j gets captured separately (i.e. a different compiler-generated class instance).
Jon Skeet has a good blog entry covering C# and java closures here; or for more detail, see his book C# in Depth, which has an entire chapter on them.
I agree with a previous answer of "all the time". When you program in a functional language or any language where lambdas and closures are common, you use them without even noticing. It's like asking "what is the scenario for a function?" or "what is the scenario for a loop?" This isn't to make the original question sound dumb, rather it's to point out that there are constructs in languages that you don't define in terms of specific scenarios. You just use them all the time, for everything, it's second nature.
This is somehow reminiscent of:
The venerable master Qc Na was walking
with his student, Anton. Hoping to
prompt the master into a discussion,
Anton said "Master, I have heard that
objects are a very good thing - is
this true?" Qc Na looked pityingly at
his student and replied, "Foolish
pupil - objects are merely a poor
man's closures."
Chastised, Anton took his leave from
his master and returned to his cell,
intent on studying closures. He
carefully read the entire "Lambda: The
Ultimate..." series of papers and its
cousins, and implemented a small
Scheme interpreter with a
closure-based object system. He
learned much, and looked forward to
informing his master of his progress.
On his next walk with Qc Na, Anton
attempted to impress his master by
saying "Master, I have diligently
studied the matter, and now understand
that objects are truly a poor man's
closures." Qc Na responded by hitting
Anton with his stick, saying "When
will you learn? Closures are a poor
man's object." At that moment, Anton
became enlightened.
(http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html)
The most simple example of using closures is in something called currying. Basically, let's assume we have a function f() which, when called with two arguments a and b, adds them together. So, in Python, we have:
def f(a, b):
return a + b
But let's say, for the sake of argument, that we only want to call f() with one argument at a time. So, instead of f(2, 3), we want f(2)(3). This can be done like so:
def f(a):
def g(b): # Function-within-a-function
return a + b # The value of a is present in the scope of g()
return g # f() returns a one-argument function g()
Now, when we call f(2), we get a new function, g(); this new function carries with it variables from the scope of f(), and so it is said to close over those variables, hence the term closure. When we call g(3), the variable a (which is bound by the definition of f) is accessed by g(), returning 2 + 3 => 5
This is useful in several scenarios. For example, if I had a function which accepted a large number of arguments, but only a few of them were useful to me, I could write a generic function like so:
def many_arguments(a, b, c, d, e, f, g, h, i):
return # SOMETHING
def curry(function, **curry_args):
# call is a closure which closes over the environment of curry.
def call(*call_args):
# Call the function with both the curry args and the call args, returning
# the result.
return function(*call_args, **curry_args)
# Return the closure.
return call
useful_function = curry(many_arguments, a=1, b=2, c=3, d=4, e=5, f=6)
useful_function is now a function which only needs 3 arguments, instead of 9. I avoid having to repeat myself, and also have created a generic solution; if I write another many-argument function, I can use the curry tool again.
Typically, if one doesn't have closures, one must define a class to carry with it the equivalent of the closure's environment, and pass it around.
For example, in a language like Lisp, one can define a function that returns a function (with a closed-over environment) to add some predefined amount to its argument thusly:
(defun make-adder (how-much)
(lambda (x)
(+ x how-much)))
and use it like this:
cl-user(2): (make-adder 5)
#<Interpreted Closure (:internal make-adder) # #x10009ef272>
cl-user(3): (funcall * 3) ; calls the function you just made with the argument '3'.
8
In a language without closures, you would do something like this:
public class Adder {
private int howMuch;
public Adder(int h) {
howMuch = h;
}
public int doAdd(int x) {
return x + howMuch;
}
}
and then use it like this:
Adder addFive = new Adder(5);
int addedFive = addFive.doAdd(3);
// addedFive is now 8.
The closure implicitly carries its environment with it; you seamlessly refer to that environment from inside the executing part (the lambda). Without closures you must make that environment explicit.
That should explain to you when you would use closures: all the time. Most instances where a class is instantiated to carry with it some state from another part of the computation and apply it elsewhere are elegantly replaced by closures in languages which support them.
One can implement an object system with closures.
Here is an example from Python's standard library, inspect.py. It currently reads
def strseq(object, convert, join=joinseq):
"""Recursively walk a sequence, stringifying each element."""
if type(object) in (list, tuple):
return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
else:
return convert(object)
This has, as parameters, a convert function and a join function, and recursively walks over lists and tuples. The recursion is implemented using map(), where the first parameter is a function. The code predates the support for closures in Python, so needs two additional default arguments, to pass convert and join into the recursive call. With closures, this reads
def strseq(object, convert, join=joinseq):
"""Recursively walk a sequence, stringifying each element."""
if type(object) in (list, tuple):
return join(map(lambda o: strseq(o, convert, join), object))
else:
return convert(object)
In OO languages, you typically don't use closures too often, as you can use objects to pass state - and bound methods, when your language has them. When Python didn't have closures, people said that Python emulates closures with objects, whereas Lisp emulates objects with closures. As an example from IDLE (ClassBrowser.py):
class ClassBrowser: # shortened
def close(self, event=None):
self.top.destroy()
self.node.destroy()
def init(self, flist):
top.bind("<Escape>", self.close)
Here, self.close is a parameter-less callback invoked when Escape is pressed. However, the close implementation does need parameters - namely self, and then self.top, self.node. If Python didn't have bound methods, you could write
class ClassBrowser:
def close(self, event=None):
self.top.destroy()
self.node.destroy()
def init(self, flist):
top.bind("<Escape>", lambda:self.close())
Here, the lambda would get "self" not from a parameter, but from the context.
In Lua and Python it's a very natural thing to do when "just coding", because the moment you reference something that's not a parameter, you're making a closure. (so most of these will be quite dull as examples.)
As for a concrete case, imagine an undo/redo system, where the steps are pairs of (undo(), redo()) closures. The more cumbersome ways of doing that might be to either: (a) Make unredoable classes have a special method with universally dorky arguments, or (b) subclass UnReDoOperation umpteen times.
Another concrete example is infinite lists: Instead of working with genericized containers, you frob a function that retrieves the next element. (this is part of the power of iterators.) In this case you can either keep just little bit of state (the next integer, for the list-of-all-nonnegative-integers or similar) or a reference to a position in an actual container. Either way, it's a function that references something that is outside itself. (in the infinite-list case, the state variables must be closure variables, because otherwise they'd be clean for every call)
I'm told there are more uses in haskell, but I've only had the pleasure of using closures in javascript, and in javascript I don't much see the point. My first instinct was to scream "oh no, not again" at what a mess the implementation must be to make closures work.
After I read about how closures were implemented (in javascript anyway), it doesn't seem quite so bad to me now and the implementation seems somewhat elegant, to me at least.
But from that I realized "closure" isn't really the best word to describe the concept. I think it should better be named "flying scope."
As one of the previous answers notes, you often find yourself using them without hardly noticing that you are.
A case in point is that they are very commonly used in setting up UI event handling to gain code reuse while still allowing access to the UI context. Here's an example of how defining an anonymous handler function for a click event creates a closure that includes the button and color parameters of the setColor() function:
function setColor(button, color) {
button.addEventListener("click", function()
{
button.style.backgroundColor = color;
}, false);
}
window.onload = function() {
setColor(document.getElementById("StartButton"), "green");
setColor(document.getElementById("StopButton"), "red");
}
Note: for accuracy it's worth noting that the closure is not actually created until the setColor() function exits.