Re: Struct Inheritence
Yes that's exactly what i needed, thanks!
Re: Get memory usage report from GC
On Saturday, 20 February 2016 at 05:55:26 UTC, Jon D wrote: On Saturday, 20 February 2016 at 05:34:01 UTC, tcak wrote: On Saturday, 20 February 2016 at 05:33:00 UTC, tcak wrote: Is there any way (I checked core.memory already) to collect report about memory usage from garbage collector? So, I can see a list of pointer and length information. Since getting this information would require another memory area in heap, it could be like logging when report is asked. My long running but idle program starts using 41.7% of memory (that's close to 3GB), and it is not obvious whether the memory is allocated by a single variable, or many variables. My mistake, it is close to 512MB. Doesn't sounds like precisely what you want, but there are summary reports of GC activity available via the "--DRT-gcopt=profile:1" command line option. More info at: http://dlang.org/spec/garbage.html --Jon I checked it out now. Yes, it is not that much useful unfortunately. The process is a daemon. stdin, stdout, and stderr are forwarded to /dev/null, thus, there is nothing like getting a text report at the end of process. I am still looking for a way to at least hook up to GC, so when it allocates, or deallocates, I could log it myself.
Re: Get memory usage report from GC
On Saturday, 20 February 2016 at 05:34:01 UTC, tcak wrote: On Saturday, 20 February 2016 at 05:33:00 UTC, tcak wrote: Is there any way (I checked core.memory already) to collect report about memory usage from garbage collector? So, I can see a list of pointer and length information. Since getting this information would require another memory area in heap, it could be like logging when report is asked. My long running but idle program starts using 41.7% of memory (that's close to 3GB), and it is not obvious whether the memory is allocated by a single variable, or many variables. My mistake, it is close to 512MB. Doesn't sounds like precisely what you want, but there are summary reports of GC activity available via the "--DRT-gcopt=profile:1" command line option. More info at: http://dlang.org/spec/garbage.html --Jon
Get memory usage report from GC
Is there any way (I checked core.memory already) to collect report about memory usage from garbage collector? So, I can see a list of pointer and length information. Since getting this information would require another memory area in heap, it could be like logging when report is asked. My long running but idle program starts using 41.7% of memory (that's close to 3GB), and it is not obvious whether the memory is allocated by a single variable, or many variables.
Status icon on Linux
I want a status icon for a Linux application. gtk.StatusIcon notes that it's deprecated (and doesn't work on MATE 1.8.2). What should I be using?
Re: 111
On 2/19/16 11:15 PM, Lisa wrote: module main; import std.stdio; import std.math; int main() { int A, B, C; writef("A = "); readf("%lf", %A); You want , not %A. Also, note that you declared A, B, C as integers, but are using %lf which is for doubles. However, readf is much smarter than scanf. You can just use %s as format specifier, and it will figure out what should happen based on the given type. -Steve
Re: Parallel example from documentation does not compile
Sadly the answer is no. This is due to https://issues.dlang.org/show_bug.cgi?id=5710 which apparently no-one is either willing or able to fix. The problem afflicts dmd, l;dc2 and I suspect gdc. cf. https://github.com/russel/Pi_Quadrature/tree/master/D for some extra detail and some workarounds. It appears I had not added this original version, but I am now fixing this. On Fri, 2016-02-19 at 21:57 +, Ish via Digitalmars-d-learn wrote: > This code snippet is from: > http://dlang.org/phobos/std_parallelism.html > --- > import std.algorithm, std.parallelism, std.range; > > void main() { > // Parallel reduce can be combined with > // std.algorithm.map to interesting effect. > // The following example (thanks to Russel Winder) > // calculates pi by quadrature using > // std.algorithm.map and TaskPool.reduce. > // getTerm is evaluated in parallel as needed by > // TaskPool.reduce. > // > // Timings on an Athlon 64 X2 dual core machine: > // > // TaskPool.reduce: 12.170 s > // std.algorithm.reduce: 24.065 s > > immutable n = 1_000_000_000; > immutable delta = 1.0 / n; > > real getTerm(int i) > { > immutable x = ( i - 0.5 ) * delta; > return delta / ( 1.0 + x * x ) ; > } > > immutable pi = 4.0 * taskPool.reduce!"a + b"( > std.algorithm.map!getTerm(iota(n)) > ); > } > > dmd compiler gives error: > /usr/include/dmd/phobos/std/parallelism.d(2624): Error: function > std.parallelism.TaskPool.reduce!"a + > b".reduce!(MapResult!(getTerm, Result)).reduce cannot get frame > pointer to D main > > Is there way to compile it? > > -Ish -- Russel. = Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.win...@ekiga.net 41 Buckmaster Roadm: +44 7770 465 077 xmpp: rus...@winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder signature.asc Description: This is a digitally signed message part
Re: 111
On Saturday, 20 February 2016 at 03:43:17 UTC, Ali Çehreli wrote: On 02/19/2016 07:37 PM, Lisa wrote: > import std.stdio; > import std.math; > > int main() > { > double a, b, c, p; > > writef("Enter a: "); > scanf("%d", ); scanf is not a safe function. It trusts the format string and assumes that 'a' really is what the programmer told it. (For example, although 'a' is not an 'int, %d means 'int' and scanf treats it as such.) The correct format identifier for double is %lf. You need to replace all three of with %lf. However, you are not writing idiomatic D code. I recommend dropping C functions altogether an taking advantage of readf(): http://ddili.org/ders/d.en/input.html Ali module main; import std.stdio; import std.math; int main() { int A, B, C; writef("A = "); readf("%lf", %A); writef("B = "); readf("%lf", %B); writef("C1= "); readf("%lf", %C); writefl("P = (%lf)", A + B + C); return 0; } It whatever doesn't work
Re: 111
On 02/19/2016 07:37 PM, Lisa wrote: > import std.stdio; > import std.math; > > int main() > { > double a, b, c, p; > > writef("Enter a: "); > scanf("%d", ); scanf is not a safe function. It trusts the format string and assumes that 'a' really is what the programmer told it. (For example, although 'a' is not an 'int, %d means 'int' and scanf treats it as such.) The correct format identifier for double is %lf. You need to replace all three of with %lf. However, you are not writing idiomatic D code. I recommend dropping C functions altogether an taking advantage of readf(): http://ddili.org/ders/d.en/input.html Ali
Re: 111
On Saturday, 20 February 2016 at 01:48:35 UTC, Ali Çehreli wrote: On 02/19/2016 03:56 PM, Lisa wrote: Can you please help me and explain how to create a program, which would find area of triangle and its perimeter? It's great to have student questions on this forum. If you don't mind telling us, which teacher and school teaches or uses D? The only one that I know of is Professor Chuck Allison at Utah Valley University. Assuming that you are given the lengths of the three sides, you can calculate the area with Heron's formula. I had used that method in this otherwise unrelated chapter: http://ddili.org/ders/d.en/invariant.html Ali import std.stdio; import std.math; int main() { double a, b, c, p; writef("Enter a: "); scanf("%d", ); writef("Enter b: "); scanf("%d", ); writef("Enter c: "); scanf("%d", ); p = a + b + c; writeln("P=", p); return 0; } I try to do just perimetr, but it doesn't work :(
Why does partial ordering of overloaded functions not take return type into account?
module main; struct ThingOne { int thing = 1; } struct ThingTwo { float thing = 2; } struct Test { ThingOne thing() { return ThingOne(); } ThingTwo thing() { return ThingTwo(); } } void main() { Test test; ThingOne thingOne = test.thing(); } test.d(35): Error: main.Test.thing called with argument types () matches both: test.d(17): main.Test.thing() and: test.d(22): main.Test.thing() Why isn't the return type checked when resolving this? Only one of the choices would actually compile so there should be no ambiguity.
Re: Installing DUB on OSX
On Thursday, 18 February 2016 at 08:18:20 UTC, Guillaume Piolat wrote: On Thursday, 18 February 2016 at 07:52:11 UTC, Joel wrote: On Thursday, 18 February 2016 at 07:11:23 UTC, Joel wrote: I had dub installed in a folder that meant I had to put 'sudo dub' to run it. I've tried to fix the problem, but where do you put it (also I tried one place, but couldn't put it in that folder)? I've now tried 'brew install dub' and 'brew upgrade dub', but they come up with, 'Warning: dub-0.9.22 already installed', or 'Error: dub 0.9.22 already installed'. What I do here: - git clone DUB to ~/Desktop/dub - built it with build.sh - put symbolic links to the binary in /usr/bin How do you do symbolic links?
Re: Modify Function Pointer to Take Additional Parameters
On Friday, 19 February 2016 at 22:34:48 UTC, Chris Wright wrote: I tested this a fair bit today, and I haven't been able to do any of the nefarious things I expected to be able to do. No overwriting variables in the caller's scope, no smashing stack pointers, etc. I was surprised by this result, but in retrospect, it's relatively obvious. The caller pushes variables onto the stack and sets the stack pointer for the callee. It wouldn't send a stack pointer that pointed into its own stack frame. Thanks for taking the time to test. The more I've thought about it, the more I wonder if there should be a restriction so that casts of function pointers/delegate maintain the same number of parameters. Even though you haven't been able to do nefarious things, it's giving a completely wrong answer than you would expect. The result of the answer might cause bad things to happen in a program. Further, to even understand what's going wrong you have to understand how the compiler is generating assembly. I've been using D for like a year or so, and I would never have been able to figure out the reason by myself. Or at least in safe code you shouldn't be able to do this.
Re: 111
On Friday, 19 February 2016 at 23:56:29 UTC, Lisa wrote: Can you please help me and explain how to create a program, which would find area of triangle and its perimeter? And for everybody - I know how to find area and perimetr, but i don't know how to write it on programming language) Can i use "scanf" in D language?
Re: 111
On Saturday, 20 February 2016 at 01:48:35 UTC, Ali Çehreli wrote: On 02/19/2016 03:56 PM, Lisa wrote: Can you please help me and explain how to create a program, which would find area of triangle and its perimeter? It's great to have student questions on this forum. If you don't mind telling us, which teacher and school teaches or uses D? The only one that I know of is Professor Chuck Allison at Utah Valley University. Assuming that you are given the lengths of the three sides, you can calculate the area with Heron's formula. I had used that method in this otherwise unrelated chapter: http://ddili.org/ders/d.en/invariant.html Ali Thank you :) I'm actually from Ukraine)
Re: Transposing a static array
On 02/19/2016 06:26 PM, maik klein wrote: > On Saturday, 20 February 2016 at 02:22:12 UTC, Ali Çehreli wrote: >> On 02/19/2016 06:00 PM, maik klein wrote: >>> How would I transpose >>> >>> float[3][2] >>> >>> to >>> >>> float[2][3] >>> >>> with http://dlang.org/phobos/std_range.html#.transposed >> auto r = arr[].map!((ref a) => a[]).array.transposed; There is a problem there. Adding the following line writeln(r.array); causes an error: core.exception.AssertError@/usr/include/dmd/phobos/std/range/primitives.d(2207): Attempting to fetch the front of an empty array of float Adding the following two lines does *not* preserve the range (first one does): writeln(r.save); writeln(r.save); Did I not need (ref a) up there? I thought it would be a reference to a float[3] element. >> writeln(r); >> } >> } >> >> Ali > > Your "Method B" is how I did it too but how do I convert it back to a > static array of float[2][3]? I don't know. :D Ali
Re: Transposing a static array
On Saturday, 20 February 2016 at 02:26:56 UTC, maik klein wrote: On Saturday, 20 February 2016 at 02:22:12 UTC, Ali Çehreli wrote: On 02/19/2016 06:00 PM, maik klein wrote: How would I transpose float[3][2] to float[2][3] with http://dlang.org/phobos/std_range.html#.transposed Because static arrays are not ranges, they must be used as slices with the help of []. The following code does the same thing in two different ways: import std.stdio; import std.range; import std.algorithm; void main() { float[3][2] arr = [ [1, 2, 3], [4, 5, 6] ]; // Method A { float[][] arr2; foreach (ref a; arr) { arr2 ~= a[]; } writeln(arr2.transposed); } // Method B { auto r = arr[].map!((ref a) => a[]).array.transposed; writeln(r); } } Ali Your "Method B" is how I did it too but how do I convert it back to a static array of float[2][3]? I don't see the point of using transposed which gives a range out if you want to put it back into a float[2][3] right away, just do a double foreach: void main(string[] args) { float[3][2] src = [[1, 2, 3], [2, 3, 4]]; float[2][3] dst; foreach (i ; 0..src.length) foreach (j ; 0..src[0].length) dst[j][i] = src[i][j]; assert(dst == [[1, 2], [2, 3], [3, 4]]); }
Re: Transposing a static array
On Saturday, 20 February 2016 at 02:22:12 UTC, Ali Çehreli wrote: On 02/19/2016 06:00 PM, maik klein wrote: How would I transpose float[3][2] to float[2][3] with http://dlang.org/phobos/std_range.html#.transposed Because static arrays are not ranges, they must be used as slices with the help of []. The following code does the same thing in two different ways: import std.stdio; import std.range; import std.algorithm; void main() { float[3][2] arr = [ [1, 2, 3], [4, 5, 6] ]; // Method A { float[][] arr2; foreach (ref a; arr) { arr2 ~= a[]; } writeln(arr2.transposed); } // Method B { auto r = arr[].map!((ref a) => a[]).array.transposed; writeln(r); } } Ali Your "Method B" is how I did it too but how do I convert it back to a static array of float[2][3]?
Re: Transposing a static array
On 02/19/2016 06:00 PM, maik klein wrote: How would I transpose float[3][2] to float[2][3] with http://dlang.org/phobos/std_range.html#.transposed Because static arrays are not ranges, they must be used as slices with the help of []. The following code does the same thing in two different ways: import std.stdio; import std.range; import std.algorithm; void main() { float[3][2] arr = [ [1, 2, 3], [4, 5, 6] ]; // Method A { float[][] arr2; foreach (ref a; arr) { arr2 ~= a[]; } writeln(arr2.transposed); } // Method B { auto r = arr[].map!((ref a) => a[]).array.transposed; writeln(r); } } Ali
Re: Create a proxy
On 02/19/2016 06:18 AM, Voitech wrote: > I was trying to use mixins for this i > created some functions but this not working don't know why Compilation errors or something else? pragma(msg) helps with debugging generated code. You can also use unittest blocks to make sure that the generated code is what you expect. > There is also a Proxy template in std.typecons but i don't understand > how it works That one makes a user-defined type to be used as another type. The example from the documentation is MyInt behaves exactly like an int by forwarding int operations to 'value': struct MyInt { private int value; mixin Proxy!value; this(int n){ value = n; } } MyInt n = 10; Support for all the following operations (++, ==, *, and more) are mixed in by Proxy: // Enable operations that original type has. ++n; assert(n == 11); assert(n * 2 == 22); Ali
Transposing a static array
How would I transpose float[3][2] to float[2][3] with http://dlang.org/phobos/std_range.html#.transposed
Re: 111
On 02/19/2016 03:56 PM, Lisa wrote: Can you please help me and explain how to create a program, which would find area of triangle and its perimeter? It's great to have student questions on this forum. If you don't mind telling us, which teacher and school teaches or uses D? The only one that I know of is Professor Chuck Allison at Utah Valley University. Assuming that you are given the lengths of the three sides, you can calculate the area with Heron's formula. I had used that method in this otherwise unrelated chapter: http://ddili.org/ders/d.en/invariant.html Ali
Re: 111
On Saturday, 20 February 2016 at 00:42:36 UTC, Chris Wright wrote: How do you calculate the area of a triangle? Same way as you'd do it by hand -- 1/2 base times height. Getting the height can be tricky sometimes though, depending on what information you know about the triangle. I like to check wikipedia for refreshers on math tricks. https://en.wikipedia.org/wiki/Triangle#Computing_the_area_of_a_triangle There's formulas to follow for almost any kind of input there... and if you have to get perimeter anyway, you are already calculating the lengths of the sides, so I'd use the convenient formula in there based on those very lengths!
Re: 111
On Sat, 20 Feb 2016 00:17:28 +, Lisa wrote: > On Saturday, 20 February 2016 at 00:15:16 UTC, Chris Wright wrote: >> On Sat, 20 Feb 2016 00:04:04 +, Lisa wrote: >> >>> On Saturday, 20 February 2016 at 00:01:47 UTC, cym13 wrote: On Friday, 19 February 2016 at 23:56:29 UTC, Lisa wrote: > Can you please help me and explain how to create a program, > which would find area of triangle and its perimeter? What do you need help for exactly? What have you tried? What do you struggle with? >>> >>> With everything, actually i need full explanation and listing of >>> programm from its beginning >> >> Is this a homework problem that was assigned to you? > > Yes, exectly. It's new for me, and i don't even know how should I start. Break the problem down into parts. First you need to get a triangle. Then you need to calculate the dimensions. How do you get the triangle? The homework problem should tell you. How do you calculate the area of a triangle? Same way as you'd do it by hand -- 1/2 base times height. Break that down further and further and you'll have that part squared away before long. How do you calculate the perimeter of a triangle? Same way as you'd do by hand -- sum of distances between corners. Again, break it into parts and you'll have a program before long. Programmers tend to be reluctant to do other people's homework for them. (People in general are reluctant to do other people's homework for them.) It would help you this week, but you'd be further out of your depth next week and you'd be pretty much bound to fail. Or you'd have a lot more work to catch up and a lot less time in which to do it.
Re: 111
On Saturday, 20 February 2016 at 00:04:04 UTC, Lisa wrote: On Saturday, 20 February 2016 at 00:01:47 UTC, cym13 wrote: On Friday, 19 February 2016 at 23:56:29 UTC, Lisa wrote: Can you please help me and explain how to create a program, which would find area of triangle and its perimeter? What do you need help for exactly? What have you tried? What do you struggle with? With everything, actually i need full explanation and listing of programm from its beginning I don't think you'll ever get the program listing here, it's just not how it works. We can help you, guide you to the solution but you are the one that has to do it otherwise it defeats the whole purpose of the exercise. First of all, programming is explaining a solution to a really dumb student (the computer). If you can't do it by hand, you can't explain it to the computer. Once you can do it by hand, decompose each step into steps as simple as possible and write them down on paper. Then it's just a matter of translating your pseudo-code on paper to real code: if it's an exercise I'm sure you have had courses and examples. Take inspiration, try things and don't hesitate to fail: nobody expects you to get it right on the first time.
Re: 111
On Friday, 19 February 2016 at 23:56:29 UTC, Lisa wrote: Can you please help me and explain how to create a program, which would find area of triangle and its perimeter? First, one can't find these unless something is given. So, what is given: sides? angles? two-dimensional coordinates? The next stop is Google for how to do that mathematically, without touching the keyboard. Once you have the above, you may have some specific difficulty expressing that in a programming language of your choice, one which Google (again) can't resolve in a few minutes. If that is the case, please state that difficulty.
Re: 111
On Saturday, 20 February 2016 at 00:15:16 UTC, Chris Wright wrote: On Sat, 20 Feb 2016 00:04:04 +, Lisa wrote: On Saturday, 20 February 2016 at 00:01:47 UTC, cym13 wrote: On Friday, 19 February 2016 at 23:56:29 UTC, Lisa wrote: Can you please help me and explain how to create a program, which would find area of triangle and its perimeter? What do you need help for exactly? What have you tried? What do you struggle with? With everything, actually i need full explanation and listing of programm from its beginning Is this a homework problem that was assigned to you? Yes, exectly. It's new for me, and i don't even know how should I start.
Re: 111
On Sat, 20 Feb 2016 00:04:04 +, Lisa wrote: > On Saturday, 20 February 2016 at 00:01:47 UTC, cym13 wrote: >> On Friday, 19 February 2016 at 23:56:29 UTC, Lisa wrote: >>> Can you please help me and explain how to create a program, >>> which would find area of triangle and its perimeter? >> >> What do you need help for exactly? What have you tried? What do you >> struggle with? > > With everything, actually i need full explanation and listing of > programm from its beginning Is this a homework problem that was assigned to you?
Re: D Grammar Parser In D
On Friday, 19 February 2016 at 23:09:11 UTC, Patience wrote: On Friday, 19 February 2016 at 22:34:22 UTC, Adam D. Ruppe wrote: On Friday, 19 February 2016 at 22:29:32 UTC, Patience wrote: Is there anything in D like https://irony.codeplex.com/ https://github.com/Hackerpilot/libdparse/ I don't want to parse d code. I want a generic parser that is written in D like how irony is written in C#. Pegged maybe? https://github.com/PhilippeSigaud/Pegged
Re: 111
On Saturday, 20 February 2016 at 00:01:47 UTC, cym13 wrote: On Friday, 19 February 2016 at 23:56:29 UTC, Lisa wrote: Can you please help me and explain how to create a program, which would find area of triangle and its perimeter? What do you need help for exactly? What have you tried? What do you struggle with? With everything, actually i need full explanation and listing of programm from its beginning
Re: 111
On Friday, 19 February 2016 at 23:56:29 UTC, Lisa wrote: Can you please help me and explain how to create a program, which would find area of triangle and its perimeter? What do you need help for exactly? What have you tried? What do you struggle with?
111
Can you please help me and explain how to create a program, which would find area of triangle and its perimeter?
Re: D Grammar Parser In D
On Friday, 19 February 2016 at 22:34:22 UTC, Adam D. Ruppe wrote: On Friday, 19 February 2016 at 22:29:32 UTC, Patience wrote: Is there anything in D like https://irony.codeplex.com/ https://github.com/Hackerpilot/libdparse/ I don't want to parse d code. I want a generic parser that is written in D like how irony is written in C#.
Re: Installing DUB on OSX
On Friday, 19 February 2016 at 11:34:33 UTC, John Colvin wrote: On Thursday, 18 February 2016 at 23:28:43 UTC, Joel wrote: On Thursday, 18 February 2016 at 16:33:51 UTC, John Colvin wrote: [...] I don't think I put 'sudo brew' at any point (I can't remember). I hope I haven't broken my OSX! [...] Did you recently upgrade OS X? Anyway, you should probably work through the suggestions from brew doctor, then brew update, then brew upgrade. I did recently upgrade OS X. I'm not sure I can do any thing with brew issues.
Re: Modify Function Pointer to Take Additional Parameters
On Fri, 19 Feb 2016 21:57:46 +, Yuxuan Shui wrote: > I don't think it's safe to convert between function pointer with > different number of arguments... It's possible to mess up the stack > frame. I tested this a fair bit today, and I haven't been able to do any of the nefarious things I expected to be able to do. No overwriting variables in the caller's scope, no smashing stack pointers, etc. I was surprised by this result, but in retrospect, it's relatively obvious. The caller pushes variables onto the stack and sets the stack pointer for the callee. It wouldn't send a stack pointer that pointed into its own stack frame.
Re: D Grammar Parser In D
On Friday, 19 February 2016 at 22:29:32 UTC, Patience wrote: Is there anything in D like https://irony.codeplex.com/ https://github.com/Hackerpilot/libdparse/
D Grammar Parser In D
Is there anything in D like https://irony.codeplex.com/
Re: Decoding Pattern to a Tuple
On 02/19/2016 11:04 AM, Ali Çehreli wrote: > can be templatized: Not ready for prime time but now it's templatized: import std.stdio; import std.string; import std.regex; import std.typecons; import std.conv; import std.algorithm; import std.range; template regexClass(T) { static if (is (T == int)) { // Warning: Treats "012" as int (value 12), not octal (value 10). enum regexClass = `[0-9]+`; } else static if (is (T == char)) { enum regexClass = `.`; } else static if (is (T == double)) { enum regexClass = `[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?`; } else { static assert(false, format("Unsupported type %s", arg)); } } string regexEscape(string s) { // TODO: Expand the array and fix the logic. enum specialRegexChars = [ '(', ')' ]; return s.map!(c => (specialRegexChars.canFind(c) ? format("[%s]", c) : format("%s", c))) .joiner .text; } auto parseDecodeArgs(Args...)(string matchedElementName) { string regexString; string tupleString = "return tuple("; size_t selectionId = 1; foreach (arg; Args) { static if (is (arg)) { regexString ~= format("(%s)", regexClass!arg); tupleString ~= format("%s[%s].to!%s, ", matchedElementName, selectionId, arg.stringof); ++selectionId; } else static if (is (typeof(arg) == string)) { regexString ~= regexEscape(arg); } else { static assert(false, format("Unsupported type %s", typeof(arg))); } } tupleString ~= ");"; return tuple(regexString, tupleString); } auto decode(Args...)(string s) { enum parseResult = parseDecodeArgs!Args("e"); enum r = ctRegex!(parseResult[0]); // pragma(msg, parseResult[0]); // pragma(msg, parseResult[1]); auto matched = s.match(r); if (matched) { foreach (e; matched) { mixin (parseResult[1]); } } return typeof(return)(); } void main() { auto t = decode!("(", int, ")", char, "(", double, ")")("(1)-(2.5)"); writeln(t); // Create a decoder for repeated use auto decoder = (string s) => decode!(int, "/", double)(s); // Decode each with the same decoder auto decoded = ["1/1.5", "2/2.5", "3/3.5"] .map!decoder; writeln(decoded); } Ali
Re: Modify Function Pointer to Take Additional Parameters
On Friday, 19 February 2016 at 22:07:25 UTC, Chris Wright wrote: If you want to cast function pointers successfully, you have to know the D calling convention. [snip] I figured there was an explanation. Definitely "here be dragons" territory. I hope I can figure out a better solution, but the behavior I'm trying to get is really just a nice to have.
Re: Struct Inheritence
On Friday, 19 February 2016 at 21:58:24 UTC, user001 wrote: Well struct don't have it, but i would like something like it but only for data, i don't need functions or anything like that just data. [...] How about struct A { int valueA; } struct B { A a; int valueB; alias a this; } struct C { B b; int valueC; alias b this; } ?
Re: Struct Inheritence
On Friday, 19 February 2016 at 21:58:24 UTC, user001 wrote: Well struct don't have it, but i would like something like it but only for data, i don't need functions or anything like that just data. struct A { int valueA; } struct B { A a; int valueB; } struct C { B b; int valueC; } C c; c.b.a.valueA; // not elegant B* b = b.a.valueA; // we can access A // alternative -- struct A { int valueA; } struct B { int valueB; } struct C { A a; B b; int valueC; } C c; c.a.valueA; // a bit more elegant but still not very, c.valueA would be prefered B* b = b.? // can't access A, unless we do some hack that assumes B always follows A in the definition Is there any way to do inheritance with structs, is there a reason why we can't extend structures like in C++? Indeed, that's very cumbersome, and that's why "alias this" was introduced! It allows you to subtype: calls to members or methods that do not belong the the main type are forwarded to the member. Unfortunately we don't have multiple alias this so you can only forward to one member but it isn't very problematic in practice as otherwise things are likely to become easy to abuse. Use it like that: import std.stdio; struct A { int valueA = 1; } struct B { A a; alias a this; int valueB = 2; } struct C { B b; alias b this; int valueC = 3; } void main(string[] args) { C c; assert(c.valueA == 1); assert(c.valueB == 2); assert(c.valueC == 3); }
Re: Modify Function Pointer to Take Additional Parameters
On Fri, 19 Feb 2016 20:45:23 +, jmh530 wrote: > I tried to use a cast (below) to modify the function pointer, but it is > printing the second number instead of the first. I find this behavior > strange... If you want to cast function pointers successfully, you have to know the D calling convention. See: https://dlang.org/spec/abi.html Notably: "The last parameter is passed in EAX [a CPU register] rather than being pushed on the stack". So foo expected an argument in EAX, and it dealt with that. Calling foo_ pushes '1' onto the stack, sets EAX to '200', and then jumps to the function address. (But note also: "The callee cleans the stack." So if you pass, say, a struct that has a destructor instead of an integer, that means the struct destructor won't be called. I was a little surprised that the stack pointer is correctly restored.) If you had more arguments, you'd find similar results -- the last argument always goes to EAX, previous arguments are pushed on the stack in order, so you're always ignoring a prefix of the arguments. But it's a byte-wise prefix, so if you change the types, you'll see more significant changes. Casting function pointers is "here be dragons" territory. Unfortunately, it's got the same syntax as routine stuff like integer truncation and class casts, so it looks deceptively safe.
Struct Inheritence
Well struct don't have it, but i would like something like it but only for data, i don't need functions or anything like that just data. struct A { int valueA; } struct B { A a; int valueB; } struct C { B b; int valueC; } C c; c.b.a.valueA; // not elegant B* b = b.a.valueA; // we can access A // alternative -- struct A { int valueA; } struct B { int valueB; } struct C { A a; B b; int valueC; } C c; c.a.valueA; // a bit more elegant but still not very, c.valueA would be prefered B* b = b.? // can't access A, unless we do some hack that assumes B always follows A in the definition Is there any way to do inheritance with structs, is there a reason why we can't extend structures like in C++?
Re: Modify Function Pointer to Take Additional Parameters
On Friday, 19 February 2016 at 20:45:23 UTC, jmh530 wrote: On Friday, 19 February 2016 at 15:00:51 UTC, jmh530 wrote: This works. But when I re-write foo to take that into account as in below, I get an error that I can't implicitly convert int function(int x) to int function(int x, int y). I don't think I had looked at what you had done carefully enough. Basically, you just define a new function and take a function pointer of that. That might be a brute force solution. I tried to use a cast (below) to modify the function pointer, but it is printing the second number instead of the first. I find this behavior strange... int foo(int x) { return x; } void main() { import std.stdio : writeln; auto foo_ = cast(int function(int x, int y)) writeln(foo_(1, 200)); //prints 200 } I don't think it's safe to convert between function pointer with different number of arguments... It's possible to mess up the stack frame. Also '(int x, int y)=>f(x)' is clearly a delegate because it refers to local variable 'f', you can't just cast it to 'int function(int, int)'.
Parallel example fron documentation does not compile
This code snippet is from: http://dlang.org/phobos/std_parallelism.html --- import std.algorithm, std.parallelism, std.range; void main() { // Parallel reduce can be combined with // std.algorithm.map to interesting effect. // The following example (thanks to Russel Winder) // calculates pi by quadrature using // std.algorithm.map and TaskPool.reduce. // getTerm is evaluated in parallel as needed by // TaskPool.reduce. // // Timings on an Athlon 64 X2 dual core machine: // // TaskPool.reduce: 12.170 s // std.algorithm.reduce: 24.065 s immutable n = 1_000_000_000; immutable delta = 1.0 / n; real getTerm(int i) { immutable x = ( i - 0.5 ) * delta; return delta / ( 1.0 + x * x ) ; } immutable pi = 4.0 * taskPool.reduce!"a + b"( std.algorithm.map!getTerm(iota(n)) ); } dmd compiler gives error: /usr/include/dmd/phobos/std/parallelism.d(2624): Error: function std.parallelism.TaskPool.reduce!"a + b".reduce!(MapResult!(getTerm, Result)).reduce cannot get frame pointer to D main Is there way to compile it? -Ish
Re: Modify Function Pointer to Take Additional Parameters
On Friday, 19 February 2016 at 15:00:51 UTC, jmh530 wrote: This works. But when I re-write foo to take that into account as in below, I get an error that I can't implicitly convert int function(int x) to int function(int x, int y). I don't think I had looked at what you had done carefully enough. Basically, you just define a new function and take a function pointer of that. That might be a brute force solution. I tried to use a cast (below) to modify the function pointer, but it is printing the second number instead of the first. I find this behavior strange... int foo(int x) { return x; } void main() { import std.stdio : writeln; auto foo_ = cast(int function(int x, int y)) writeln(foo_(1, 200)); //prints 200 }
Re: Decoding Pattern to a Tuple
On 02/19/2016 10:10 AM, Nordlöw wrote: Have anybody put together a generalised form of findSplit that can split and decode using a compile time parameters somewhat like "(1)-(2.0)".decode!("(", int, ")", char, "(", double, ")") evaluates to to a tuple!(int, char, double) with value tuple(1, '-', 2.0) The following toy program works with that particular case but can be templatized: import std.stdio; import std.string; import std.regex; import std.typecons; import std.conv; auto decode(string s) { // Warning: Treats "012" as int (value 12), not octal (value 10). enum intClass = `[0-9]+`; enum charClass = `.`; // Found on the internet: enum floatClass = `[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?`; enum expr = format(`[(](%s)[)](%s)[(](%s)[)]`, intClass, charClass, floatClass); enum r = ctRegex!expr; auto matched = s.match(r); if (matched) { foreach (e; matched) { // We are ignoring potential other matches on the same line and // returning just the first match. (Of course, no loop is needed.) return tuple(e[1].to!int, e[2].to!char, e[3].to!double); } } return Tuple!(int, char, double)(); } void main() { auto t = decode("(1)-(2.5)"); writeln(t); } Ali
Decoding Pattern to a Tuple
Have anybody put together a generalised form of findSplit that can split and decode using a compile time parameters somewhat like "(1)-(2.0)".decode!("(", int, ")", char, "(", double, ")") evaluates to to a tuple!(int, char, double) with value tuple(1, '-', 2.0)
Re: Modify Function Pointer to Take Additional Parameters
On Friday, 19 February 2016 at 14:21:26 UTC, Kagamin wrote: int bar(int x) { return x; } int baz(int x, int y) { return bar(x); } void main() { import std.stdio : writeln; int function(int x, int y) foo_bar = writeln(foo_bar(1, 2)); } This works. But when I re-write foo to take that into account as in below, I get an error that I can't implicitly convert int function(int x) to int function(int x, int y). auto foo(T)(T f) { static if (is(T == fp2)) { return f; } else static if (is(T == fp1)) { int function(int x, int y) f_ = f; return f_; } else { return 0; } }
Re: Modify Function Pointer to Take Additional Parameters
On Friday, 19 February 2016 at 11:26:56 UTC, Nicholas Wilson wrote: Like alias fp1 = int function(int x); alias fp2 = int function(int x, int y); auto foo(T)(T f) { static if (is(T == fp2)) return f; else static if (is(T == fp1)) { return int function(int x, int y) => f(x); } else return 0; } ? This code doesn't compile for me. I have to adjust it to return function int(int x, int y) => f(x); and then it complains that it's a delegate.
Re: multi-dimensional dynamic arrays
On Friday, 19 February 2016 at 14:26:25 UTC, Steven Schveighoffer wrote: Try ub[0].length = 3. You are trying to change the length on one of the static arrays. yes, right these compile. I was surpised it wouldn't accept the append with just an int. int[1][][1] ubb; ubb[0].length = 3; ubb[0] ~= [5]; If you had more than 1 as a static dimension, then you would have to change the length of *each* of the elements. Arrays in D, are actually quite simple. Any time you see: T[] It's a dynamic array of T. Any time you see: T[N] Where N is a compile-time integer, it's a static array of T. So dissecting your type: int[1][][1] So the outer-most T is int[1][]. You have a single instance of this, in a static array. At the next level, T is int[1], where you have a dynamic array of these. Finally, at the 3rd level, T is int, you have a single element in a static array of int. -Steve
Re: multi-dimensional dynamic arrays
On 2/19/16 8:53 AM, Jay Norwood wrote: On Friday, 19 February 2016 at 07:59:29 UTC, Jonathan M Davis wrote: .. Or you could do something really wonky like auto arr = new int[][2][](5); which would be a dynamic array of length 5 which holds static arrays of length 2 which hold dynamic arrays which are null. In my case, int [1][][1] ub;, there is only one dynamic dimension, but if I try to use .length to change the length, ub.length = 3, the compiler doesn't like that. Try ub[0].length = 3. You are trying to change the length on one of the static arrays. If you had more than 1 as a static dimension, then you would have to change the length of *each* of the elements. Arrays in D, are actually quite simple. Any time you see: T[] It's a dynamic array of T. Any time you see: T[N] Where N is a compile-time integer, it's a static array of T. So dissecting your type: int[1][][1] So the outer-most T is int[1][]. You have a single instance of this, in a static array. At the next level, T is int[1], where you have a dynamic array of these. Finally, at the 3rd level, T is int, you have a single element in a static array of int. -Steve
Re: Modify Function Pointer to Take Additional Parameters
On Friday, 19 February 2016 at 05:41:01 UTC, jmh530 wrote: void main() { import std.stdio : writeln; auto foo_bar = foo(); writeln(qux(1, 2, foo_bar)); //compiler error writeln(qux(1, 2, )); } int bar(int x) { return x; } int baz(int x, int y) { return bar(x); } void main() { import std.stdio : writeln; int function(int x, int y) foo_bar = writeln(foo_bar(1, 2)); }
Re: Duration at runtime
On 2/18/16 11:36 PM, Zekereth wrote: On Friday, 19 February 2016 at 04:21:43 UTC, Zekereth wrote: On Friday, 19 February 2016 at 04:16:23 UTC, Adam D. Ruppe wrote: On Friday, 19 February 2016 at 04:08:02 UTC, Zekereth wrote: How is seconds able to be read at compile time but unitType cannot? "seconds" is a literal value that the compiler knows about. unitType is a variable that might change between its declaration and use (it doesn't here, but the compiler doesn't check if it actually does, just if it *can*), so the compiler doesn't allow it. Thanks a lot Adam! So is there a way around this?. I want duration to be configurable at runtime. Never mind I found a better solution to my problem by storing a Duration instead of the unitType. Works just fine. Thanks a lot I appreciate your help! Because it might help with some future issue: Instead of auto, declare the unitType as immutable or enum: immutable unitType = "seconds"; enum unitType = "seconds"; Then the compiler knows it won't change. -Steve
Create a proxy
Hi, I'm trying to create a proxy with automatic method generation . Let say i hava Service object which can be Local service and Remote service. f.e: interface Service{ string serviceInfo(); } interface LocalService:Service{ int doSmth(string param); } class LocalServiceImpl:LocalService{ override string serviceInfo(){ return "i am local"; } override int doSmth(string param){ return param.lenght; } } And now i want to create a proxy, which for client is visible as LocalService class RemoteServiceProxy:LocalService{ Serializer serializer; HttpClient client; Deserializer deserializer this(Serializer serializer,Deserializer deserializer,HttpClient client){ this.serializer=serializer; this.client=client; this.deserializer=deserializer; } override string serviceInfo(){ return "i am remote"; } override int doSmth(string param){ string json= serializer.toJson!(doSmth,int,param)(); string response=client.send(json); return deserializer.fromJson!(response,int)(); } } So RemoteServiceProxy should serialize method name, return type and parameters and send it to some server. On server this should be executed (for now i don't care about errors) and returned as proper value. The problem is i don't want to override every remote service method i will create in interface (LocalService) i want them to be generated depending on return, and parameter types. It will always the same schema: serialize ... http request ... deserialize ... return value (throw Excepion). How to handle this corectly ? I was trying to use mixins for this i created some functions but this not working don't know why string createFunction(R, alias name)(){ static if(is(R==void)){ return mixin(createVoidFunction(name)()); } static if(!is(R==void)){ return mixin(createNonVoidFunction!(R,name)()); } } string createVoidFunction(alias name)(){ return format(q{ void %s(){ writeln(" im void function"); } },name); } string createNonVoidFunction(R,alias name)(){ return format(q{ %s %s(){ writeln("im non void function"); return %s; } }, R.stringof,name,R.init); } unittest{ mixin(createFunction!(int,"nonVoid")()); } There is also a Proxy template in std.typecons but i don't understand how it works or even can it be used in this case. How to handle this ?
Re: Arrays of noncopyables/Invalid memory operation
On Thursday, 18 February 2016 at 01:14:00 UTC, ZombineDev wrote: https://issues.dlang.org/show_bug.cgi?id=15661. I suggest testing this code again with a newer compiler (see my answer in the other thread - http://forum.dlang.org/post/omfyqfulgyzbrxlzr...@forum.dlang.org). Thanks -- I might get around to that at some point, but for now I'm ok waiting for pre-built binaries unless it becomes more of an issue (I've diverted far off what I need to be working on already). The "Invalid memory operation" error is thrown only by the GC (AFAIK) when the user tries something unsupported like allocating or freeing in a destructor, while a GC collection is being run. I think that it's not possible to trigger it in @nogc code. From a short debug session, I managed to find out that it crashes on the `++foos.length` line, somewhere inside this function: https://github.com/D-Programming-Language/druntime/blob/e47a00bff935c3f079bb567a6ec97663ba384487/src/rt/lifetime.d#L1265. Unfortunately I currently don't have enough time to investigate further. Can you please file a bugzilla issue with this test case? Done: https://issues.dlang.org/show_bug.cgi?id=15705 Thanks for the help!
Re: Arrays of noncopyables/Invalid memory operation
On Friday, 19 February 2016 at 01:30:13 UTC, H. S. Teoh wrote: Suppose the array gets moved sometime after i=500 because it ran out of space in the current memory location. Since there is another slice middleSlice pointing at the old data, it's not just a matter of *moving* the elements over to the new location; they have to be *copied* over so that there are now two copies of the original elements -- the GC doesn't know whether func may try to access the original elements through middleSlice, so it cannot just move them. Only when middleSlice goes out of scope, can the old elements be destructed. So we see that when an array is grown, the elements cannot simply be moved to the new location; we must make copies of them, otherwise any slice of the old data will become invalid. So after an array is moved, there will be two copies of data, and if the original elements are unreferenced after all, the GC will call the dtors when it runs the next collection cycle. Then when the new elements become unreferenced, the dtors will be called again at the following collection cycle, on the new copies of the elements. So it seems that the conclusion is that it is indeed unsafe to store non-copyable objects in an array which might grow (though it would be nice if attempting to do so was a compiler error, like it is with std.container.Array). I've starting creating a custom "Vector" type with value semantics which is move-aware, so hopefully that will address my needs. Thanks for all the help, folks!
Re: Example of code with manual memory management
https://dlang.org/phobos/std_container.html and corresponding code in phobos. Though recently allocators were introduced and containers are going to be written with support for allocators.
Re: multi-dimensional dynamic arrays
On Friday, 19 February 2016 at 07:59:29 UTC, Jonathan M Davis wrote: .. Or you could do something really wonky like auto arr = new int[][2][](5); which would be a dynamic array of length 5 which holds static arrays of length 2 which hold dynamic arrays which are null. In my case, int [1][][1] ub;, there is only one dynamic dimension, but if I try to use .length to change the length, ub.length = 3, the compiler doesn't like that. int[1][][1] ubb; ubb.length = 3; src\app.d(13,5): Error: constant ubb.length is not an lvalue dmd failed with exit code 1. So, is there some supported syntax to set the length of the internal dimension, or to append to it?
Example of code with manual memory management
Hi, I am looking for example of types where memory management is manual, and the type supports operator overloading, etc. Grateful if someone could point me to sample example code. Thanks and Regards Dibyendu
Re: Installing DUB on OSX
On Thursday, 18 February 2016 at 23:28:43 UTC, Joel wrote: On Thursday, 18 February 2016 at 16:33:51 UTC, John Colvin wrote: [...] I don't think I put 'sudo brew' at any point (I can't remember). I hope I haven't broken my OSX! [...] Did you recently upgrade OS X? Anyway, you should probably work through the suggestions from brew doctor, then brew update, then brew upgrade.
Re: Modify Function Pointer to Take Additional Parameters
On Friday, 19 February 2016 at 05:41:01 UTC, jmh530 wrote: I'm trying to write a function that will adjust the parameters of a function pointer. I think the problem is that it defaults to a delegate not that it cannot be one does clarifying this to the compiler work Like alias fp1 = int function(int x); alias fp2 = int function(int x, int y); auto foo(T)(T f) { static if (is(T == fp2)) return f; else static if (is(T == fp1)) { return int function(int x, int y) => f(x); } else return 0; } ?
Re: multi-dimensional dynamic arrays
On Friday, February 19, 2016 06:54:51 Jay Norwood via Digitalmars-d-learn wrote: > Strange to me that this compiles, since I would expect there to > be some C-like limitation on the position of the unspecified > dimension. Is allowing this somehow useful? > > int[1][][1] ub; > writeln("ub",ub); You can have dynamic arrays of static arrays. In this case, you have a static of dynamic arrays of static arrays. Alternatively, you could do something like auto arr = new int[1][](5); which would be a dynamic array of length 5 which holds static arrays of length 1. Or you could do something really wonky like auto arr = new int[][2][](5); which would be a dynamic array of length 5 which holds static arrays of length 2 which hold dynamic arrays which are null. All kinds of wacky combinations are possible. Now, are they _useful_? Well, that's another question entirely. Personally, I wouldn't use constructs like that, because they're too weird and too easy to screw up, but it wouldn't surprise me if someone at some point found a use for them. Personally, I tend to dislike even using multidimensional static arrays, because it's so easy to confuse the dimensions. e.g. int[5][3] arr; assert(arr.length == 3); assert(arr[0].length == 5); And the more complicated the array declaration, the more likely it is that you're going to screw it up - either in how it's declared or in how it's accessed. But the type system will let you do all kinds of crazy combinations if you really want to. - Jonathan M Davis