Re: Should % ever "overflow"?
On Sunday, 26 June 2016 at 04:25:07 UTC, "Smoke" Adams wrote: Languages: C#: https://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx Java: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3 C11: http://www.open-std.org/jtc1/sc22/wg14/www/docs/C99RationaleV5.10.pdf (See 6.5.5 for update on % operator, mentioning, example at 7.20.6). Python2: https://docs.python.org/2/reference/expressions.html Python3: https://docs.python.org/3/reference/expressions.html CPUs: Arm7(eeabi): https://github.com/wayling/xboot-clone/blob/master/src/arch/arm/lib/gcc/__aeabi_idivmod.S Arm7(Darwin): http://opensource.apple.com//source/clang/clang-163.7.1/src/projects/compiler-rt/lib/arm/modsi3.S Mips: http://www.mrc.uidaho.edu/mrc/people/jff/digital/MIPSir.html (See DIV instruction) X86: http://x86.renejeschke.de/html/file_module_x86_id_137.html Now I'm sure there are a weird CPU that isn't produced since the 80s and that D will never support that do it in some other way, but for all platforms that matter today, this isn't the case. This is not MY definition, this is the definition everybody except you uses? Even PHP get this right (http://php.net/manual/en/language.operators.arithmetic.php). Now champion, what do you have supporting your definition ? http://mathworld.wolfram.com/Congruence.html https://en.wikipedia.org/wiki/Modulo_operation https://en.wikipedia.org/wiki/Modular_arithmetic http://stackoverflow.com/questions/1082917/mod-of-negative-number-is-melting-my-brain https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=6422581 http://www.mathworks.com/help/matlab/ref/mod.html?requestedDomain=www.mathworks.com Except for mathematica, these are all irrelevant. The claim is that programming languages and CPU define % in some way, not that mathematician do it the same way. Please read this again (you may want to use you finger to make sure you) : This isn't a proof, this is a definition. This is the definition that is used by all programming languages out there and all CPUs. It isn't going to change because someone on the internet think he has a better definition that provide no clear advantage over the current one. You mention you had information supporting that this was not true. It is very easy to debunk. You could for instance provide a link to a CPU that do NOT do the % operation that way. I was able to demonstrate to you that all major CPUs and many major languages do it that way (see there is a claim and evidence to support it, it is how arguing works). The best you've been able to present is a DSL (mathematica) and no CPU. Bonus points for the stackoverflow question, which isn't a spec and supports my point: languages and CPU do it that way. Once again, it is to wonder if you actually understand what you are responding to. Of course, I don't expect a neanderthal like yourself to understand that. Have fun lemming. Oh, hey, I'm going to define that your an idiot! Thanks for agreeing with me. I see I've hurt your feelings. That's ok, you'll survive. Next time, try make sure to understand the difference between a definition and a proof, and I won't have to point to you, and your feeling won't be hurt next time.
Re: Should % ever "overflow"?
What deadalnix (how did you choose a nickname that is more difficult to write than your given name anyway?) said was that the definition of % only makes sense if, for every n and every m: (n/m)+(n%m)=n What this means is that, if n/m is rounded up for negative numbers, n%m must be negative. Since n/m and n%m are, usually, implemented by the CPU's hardware, performance dictates that we do whatever it is that the CPU is doing. On most modern CPUs, n/m rounds up for negative results, and n%m is negative. So, we can do it your way. This would mean: 1. Losing performance for every division and modulus that *might* be negative and 2. Being different than other programming languages out there or we can do what we're doing. Shachar
Re: Should % ever "overflow"?
On Sunday, 26 June 2016 at 03:54:28 UTC, deadalnix wrote: On Sunday, 26 June 2016 at 02:05:53 UTC, "Smoke" Adams wrote: On Sunday, 26 June 2016 at 00:31:29 UTC, deadalnix wrote: On Saturday, 25 June 2016 at 23:01:00 UTC, "Smoke" Adams wrote: This proves nothing. This isn't a proof, this is a definition. This is the definition that is used by all programming languages out there and all CPUs. It isn't going to change because someone on the internet think he has a better definition that provide no clear advantage over the current one. Again, no proof at all Either can't read or you can't think. Which is it ? and inaccurate. Not every programming language or cpu does this. Please don't make up facts to support your "definitions" and desires. Having a negative modulo is just ignorant. Languages: C#: https://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx Java: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3 C11: http://www.open-std.org/jtc1/sc22/wg14/www/docs/C99RationaleV5.10.pdf (See 6.5.5 for update on % operator, mentioning, example at 7.20.6). Python2: https://docs.python.org/2/reference/expressions.html Python3: https://docs.python.org/3/reference/expressions.html CPUs: Arm7(eeabi): https://github.com/wayling/xboot-clone/blob/master/src/arch/arm/lib/gcc/__aeabi_idivmod.S Arm7(Darwin): http://opensource.apple.com//source/clang/clang-163.7.1/src/projects/compiler-rt/lib/arm/modsi3.S Mips: http://www.mrc.uidaho.edu/mrc/people/jff/digital/MIPSir.html (See DIV instruction) X86: http://x86.renejeschke.de/html/file_module_x86_id_137.html Now I'm sure there are a weird CPU that isn't produced since the 80s and that D will never support that do it in some other way, but for all platforms that matter today, this isn't the case. This is not MY definition, this is the definition everybody except you uses? Even PHP get this right (http://php.net/manual/en/language.operators.arithmetic.php). Now champion, what do you have supporting your definition ? Your a moron. I guess you think just because everyone believes in Santa Clause it means he exists? http://mathworld.wolfram.com/Congruence.html https://en.wikipedia.org/wiki/Modulo_operation https://en.wikipedia.org/wiki/Modular_arithmetic http://stackoverflow.com/questions/1082917/mod-of-negative-number-is-melting-my-brain https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=6422581 http://www.mathworks.com/help/matlab/ref/mod.html?requestedDomain=www.mathworks.com It's one thing to claim that the sign of the modulo is the same as the sign of the divisor, but entirely different to claim the modulo should be negative. Of course, I don't expect a neanderthal like yourself to understand that. Have fun lemming. Oh, hey, I'm going to define that your an idiot! Thanks for agreeing with me.
Re: GSoC Summer of Code Update
On Friday, 24 June 2016 at 17:26:19 UTC, Craig Dillabaugh wrote: Just wanted to congratulate our 4 Google Summer of Code students who have now officially all passed their mid-term evaluations. So congrats to Lodovico, Wojciech, Jeremy, and Sebastian for making it this far, and thanks to the mentors Robert, Ilya, Adam and Russel for keeping them on the right track. The students are producing some good work and I am excited about the impact they will have on the community going forward. Craig It's great that things are going smoothly so far, in no small way due to you Craig.
Re: Should % ever "overflow"?
On Sunday, 26 June 2016 at 02:05:53 UTC, "Smoke" Adams wrote: On Sunday, 26 June 2016 at 00:31:29 UTC, deadalnix wrote: On Saturday, 25 June 2016 at 23:01:00 UTC, "Smoke" Adams wrote: This proves nothing. This isn't a proof, this is a definition. This is the definition that is used by all programming languages out there and all CPUs. It isn't going to change because someone on the internet think he has a better definition that provide no clear advantage over the current one. Again, no proof at all Either can't read or you can't think. Which is it ? and inaccurate. Not every programming language or cpu does this. Please don't make up facts to support your "definitions" and desires. Having a negative modulo is just ignorant. Languages: C#: https://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx Java: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3 C11: http://www.open-std.org/jtc1/sc22/wg14/www/docs/C99RationaleV5.10.pdf (See 6.5.5 for update on % operator, mentioning, example at 7.20.6). Python2: https://docs.python.org/2/reference/expressions.html Python3: https://docs.python.org/3/reference/expressions.html CPUs: Arm7(eeabi): https://github.com/wayling/xboot-clone/blob/master/src/arch/arm/lib/gcc/__aeabi_idivmod.S Arm7(Darwin): http://opensource.apple.com//source/clang/clang-163.7.1/src/projects/compiler-rt/lib/arm/modsi3.S Mips: http://www.mrc.uidaho.edu/mrc/people/jff/digital/MIPSir.html (See DIV instruction) X86: http://x86.renejeschke.de/html/file_module_x86_id_137.html Now I'm sure there are a weird CPU that isn't produced since the 80s and that D will never support that do it in some other way, but for all platforms that matter today, this isn't the case. This is not MY definition, this is the definition everybody except you uses? Even PHP get this right (http://php.net/manual/en/language.operators.arithmetic.php). Now champion, what do you have supporting your definition ?
Re: Project Highlight: The PowerNex Kernel
On Saturday, 25 June 2016 at 12:34:04 UTC, ZombineDev wrote: On Friday, 24 June 2016 at 21:36:27 UTC, Wild wrote: On Friday, 24 June 2016 at 14:11:43 UTC, Mike Parker wrote: On Friday, 24 June 2016 at 14:09:12 UTC, Mike Parker wrote: [...] And the reddit thread is here: https://www.reddit.com/r/programming/comments/4pn19m/from_the_d_blog_project_highlight_the_powernex/ Someone posted it to Hacker News: https://news.ycombinator.com/item?id=11969891 Also on Phoronix: http://phoronix.com/scan.php?page=news_item=PowerNex-D-Lang Congrats :) OS news too: http://www.osnews.com/comments/29268
Re: Should % ever "overflow"?
On Sunday, 26 June 2016 at 00:31:29 UTC, deadalnix wrote: On Saturday, 25 June 2016 at 23:01:00 UTC, "Smoke" Adams wrote: This proves nothing. This isn't a proof, this is a definition. This is the definition that is used by all programming languages out there and all CPUs. It isn't going to change because someone on the internet think he has a better definition that provide no clear advantage over the current one. Again, no proof at all and inaccurate. Not every programming language or cpu does this. Please don't make up facts to support your "definitions" and desires. Having a negative modulo is just ignorant.
Re: Should % ever "overflow"?
On 26.06.2016 02:54, Guillaume Boucher wrote: On Friday, 24 June 2016 at 20:43:38 UTC, deadalnix wrote: Most reasonable is numerator = quotient * divisor + remainder Which means it can be negative. Depends on the definition. If division truncates towards negative infinity, the remainder will always be nonegative (in case of a positive divisor). I personally find rounding towards negative infinity the most practical; every time I used modulo, I wanted the result to be in the range [0, divisor). Python does it this way and I find it very convenient. I agree, but unfortunately signed integer division in D follows C's convention.
Re: Slice expressions - exact evaluation order, dollar
On 17.06.2016 21:59, kinke wrote: Most interesting IMO though is the question when the slicee's pointer is to be loaded. This is only relevant if the base is an lvalue and may therefore be modified when evaluating the bound expressions. Should the returned slice be based on the slicee's buffer before or after evaluating the bounds expressions? This has been triggered by https://github.com/ldc-developers/ldc/issues/1433 as LDC loads the pointer before evaluating the bounds. Evaluation order should be strictly left-to-right. DMD and GDC get it wrong here.
Re: Should % ever "overflow"?
On Friday, 24 June 2016 at 20:43:38 UTC, deadalnix wrote: Most reasonable is numerator = quotient * divisor + remainder Which means it can be negative. Depends on the definition. If division truncates towards negative infinity, the remainder will always be nonegative (in case of a positive divisor). I personally find rounding towards negative infinity the most practical; every time I used modulo, I wanted the result to be in the range [0, divisor). Python does it this way and I find it very convenient.
Re: DbI checked integral
On 6/25/16 7:50 PM, Meta wrote: On Saturday, 25 June 2016 at 21:46:23 UTC, deadalnix wrote: On Saturday, 25 June 2016 at 14:38:43 UTC, Robert burner Schadek wrote: I think there is a major problem with the proposed design. when Checked!(int, void) is to behave as an int, why do we need it in the first place. I mean we have int as a basic type. Can't we do: alias Int = int; alias Int = Checked!(int, SomeUsefulHook); On second thought, the only feature of Checked!(int, void) is to be a slower int ;-) IMO the default CheckedInt!(int, void) needs a NaN like init/failure state. After any operation that overflows the value should be NaN. IMO this is the same problem as for the test function with no arguments. The other thread Deadalnix is referring to, for context: http://forum.dlang.org/thread/skqcudmkvqtejmofx...@forum.dlang.org Shameless plug: Andrei your input is needed I'm okay with eliminating the zero-parameters version following an appropriate deprecation cycle. It's probably useless. -- Andrei
Re: Should % ever "overflow"?
On Saturday, 25 June 2016 at 23:01:00 UTC, "Smoke" Adams wrote: This proves nothing. This isn't a proof, this is a definition. This is the definition that is used by all programming languages out there and all CPUs. It isn't going to change because someone on the internet think he has a better definition that provide no clear advantage over the current one.
Re: DbI checked integral
On Saturday, 25 June 2016 at 21:46:23 UTC, deadalnix wrote: On Saturday, 25 June 2016 at 14:38:43 UTC, Robert burner Schadek wrote: I think there is a major problem with the proposed design. when Checked!(int, void) is to behave as an int, why do we need it in the first place. I mean we have int as a basic type. Can't we do: alias Int = int; alias Int = Checked!(int, SomeUsefulHook); On second thought, the only feature of Checked!(int, void) is to be a slower int ;-) IMO the default CheckedInt!(int, void) needs a NaN like init/failure state. After any operation that overflows the value should be NaN. IMO this is the same problem as for the test function with no arguments. The other thread Deadalnix is referring to, for context: http://forum.dlang.org/thread/skqcudmkvqtejmofx...@forum.dlang.org Shameless plug: Andrei your input is needed
Re: Should % ever "overflow"?
On Friday, 24 June 2016 at 20:43:38 UTC, deadalnix wrote: On Friday, 24 June 2016 at 20:33:45 UTC, Andrei Alexandrescu wrote: In a checked environment, division may "overflow", e.g. -6 / 2u must be typed as uint but is not representable properly one. How about remainder? I suppose one can make the argument that remainder should never overflow (save for rhs == 0), because it could be defined with either a positive or negative denominator (which is not part of the result). What's the most reasonable behavior? Andrei Most reasonable is numerator = quotient * divisor + remainder Which means it can be negative. This proves nothing. Wiki: For a ***positive integer n***, two integers a and b are said to be congruent modulo n, written: a ≡ b ( mod n ) , {\displaystyle a\equiv b{\pmod {n}},\,} a\equiv b{\pmod {n}},\, if their difference a − b is an integer multiple of n (or n divides a − b). The number n is called the modulus of the congruence. For any "negative" remainder, all one has to do is subtract one from the divisor: quotient*(divisor - 1 + 1) + remainder = quotient*new_divisor + pos_remainder where new_divisor = divisor - 1, pos_remainder = quotient + remainder There are problems with allowing the remainder to be negative and it is generally best to restrict it to positive values. e.g., 129 = 2*52 + 25 OR 3*52 - 27. In the second case, we have 129/52i = 3? Basically by restricting to positive integers, we have a more natural interpretation and relationship to floor and ceil functions and we don't have to worry about it being negative(think of using in in an array indexing scheme),
[Issue 12357] Untyped string variable fails silently. No compiler warning given.
https://issues.dlang.org/show_bug.cgi?id=12357 Walter Brightchanged: What|Removed |Added Keywords||pull CC||bugzi...@digitalmars.com --
Re: Call to Action: making Phobos @safe
On 6/25/2016 3:44 PM, Walter Bright wrote: 4. Add @safe to the unittest A unittest that is deliberately unsafe should be annotated with @system. Meaning that any un-annotated unittest needs corrective action one way or the other.
Re: Call to Action: making Phobos @safe
Debugging tip: Templates should almost never be marked @safe or @trusted, as the safety should be inferred. However, to isolate down where the unsafe code actually is, add @safe temporarily to the template declaration. Then, the compiler will tell you which line in the template is unsafe.
Call to Action: making Phobos @safe
Andrei identified a key blocker for D adoption is the incomplete implementation of @safe. I'm working on the compiler end. But Phobos has a lot of code that is pointlessly not @safe, making it frustrating to write @safe code that calls Phobos. Some are listed in Bugzilla, most are not. So here's what to do: 1. Pick a module, any module, let's say 'std.foo'. 2. Compile it: dmd -unittest -main std/foo and run: foo to verify that the unittests work. 3. Take a look at foo.d and look for a unittest that is not marked @safe. 4. Add @safe to the unittest 5. Do Step 2 on it. 6. If it works, submit a PR with the annotation (well, try to collect a few of these in one module) 7. If it doesn't work, find out where the unsafe code is and fix it, and submit a PR. I've submitted maybe a dozen PRs against Phobos over the last day from doing this. It's only a start.
Re: Slice expressions - exact evaluation order, dollar
Ping. Let's clearly define these hairy evaluation order details and add corresponding tests; that'd be another advantage over C++.
[Issue 6278] Regression(2.054 beta): 'in' contract inheritance doesn't work with safe code
https://issues.dlang.org/show_bug.cgi?id=6278 --- Comment #16 from Walter Bright--- (In reply to hsteoh from comment #15) > Shouldn't it be ContractError? That was my thought, too. The problem with Error (and ContractError is derived from Error) is that it is not necessary for unwinding to occur, i.e. no destructors necessarily get called between the throw and the catch. I am concerned this may leave the program in an indeterminate state if ContractErrors are caught and then the program proceeds as normal. Hence ContractException. (yes, yebblies, it was your idea!) --
Re: GTKD - CSS class color "flash" delay
On Saturday, 25 June 2016 at 21:57:35 UTC, TheDGuy wrote: But i want to flash (e.g. change the CSS class) the buttons one by one and not all at the sime time? How am i going to do that? Okay, i tried it with a new private int-variable which contains the current index of the for-loop, like this: private void letButtonsFlash(){ foreach(Button btn;bArr){ btn.setSensitive(false); } for(int i = 0; i < level; i++){ index = i; //index is public Button currentButton = bArr[rndButtonBlink[i]]; ListG list = currentButton.getStyleContext().listClasses(); string CSSClassName = to!string(cast(char*)list.next().data); currentButton.getStyleContext().addClass(CSSClassName ~ "-flash"); Timeout t = new Timeout(_delay,1,false); } foreach(Button btn;bArr){ btn.setSensitive(true); } } bool timeout_delay(){ Button currentButton = bArr[rndButtonBlink[index]]; ListG list = currentButton.getStyleContext().listClasses(); string CSSClassName = to!string(cast(char*)list.next().data); currentButton.getStyleContext().removeClass(CSSClassName ~ "-flash"); return false; } But now the strange thing happens, that the first button lights up as expected but the second button remains at its "flash color" and doesn't go back to normal color, i don't understand why this happens? Any ideas?
Re: core.checkedint
On Saturday, 25 June 2016 at 01:49:22 UTC, Andrei Alexandrescu wrote: On 06/24/2016 09:42 PM, Andrei Alexandrescu wrote: long x = -1; auto y = array.length + x; I would be hard pressed to acknowledge that as an overflow that needs to be dynamically signaled. And the beauty of two's complement is that indeed it just works. To clarify: if array.length is 0, then indeed that should be signaled as an error. But otherwise it should just go through, no overflow. -- Andrei I'm curious how one attempts to handle overflow detection in a user-level implementation. It seems to me that such calculations are much better handled at the hardware level -- and that means, in the compiler. To wit, I'm looking at some old processor manuals I happen to have sitting around, since they tend to be quite descriptive about such details. My pdp-11 processor handbook says about the V (overflow) and C (carry) status bits in an ADD instruction: V: set if there was arithmetic overflow as a result of the operation; that is both operands were of the same sign and the result was of the opposite sign; cleared otherwise C: set if there was a carry from the most significant bit of the result; cleared otherwise I guess this is just assuming both operands are signed. It doesn't talk about a separate ADDU (add unsigned) instruction, so I guess you'd have to just use ADD and interpret the flags appropriately for that situation. The point is, there are two separate flags involved, and they need to be thought about separately and in detail in such contexts. In the MC68020 32-Bit Microprocessor User's Manual, Appendix A ("Condition Codes Computation") is really nice because it is precise and goes right down to the bottom-most detail, listing the logical equations used to set such flags. For instance, for the ADD instruction, the V and C flags are set according to these logical equations: V = (Sm and Dm and (not Rm)) or ((not Sm) and (not Dm) and Rm) C = (Sm and Dm) or ((not Rm) and Dm) or (Sm and (not Rm)) where: Sm = source (first operand) most significant bit Dm = destination (second operand) most significant bit Rm = result most significant bit (I've added parentheses to what is presented in the book, assuming that logical AND is of higher precedence than logical OR.) I'm assuming that once again, these flags are being set on the assumption that both operands are signed, as I see no separate ADDU instruction. My points are: * correct overflow detection involves an awful lot of bit-fiddling * the V (overflow) bit is *not* the same as the C (carry) bit that everyone first thinks about when considering whether or not a simple add calculation overflowed I had to wonder, how is this handled at the user level in a checkedint implementation? Do you perform a lot of data masking and testing in user-level code? Or do you depend on accessing the machine's hardware flags register and hoping it hasn't changed in between when you executed the compiled ADD instruction and when you attempt to access it from high-level code? I just checked the implementations of adds() and addu() here: https://github.com/dlang/druntime/blob/master/src/core/checkedint.d They don't seem to have quite the complexity of the logical equations I just showed. Not that they're necessarily incorrect as they stand; I'm just curious.
Re: GTKD - CSS class color "flash" delay
On Saturday, 25 June 2016 at 20:39:53 UTC, Mike Wey wrote: The constructor accepts an delegate, witch can access it's context so it has access to some of the data. The functions from GTK are also available like Timeout.add from the linked tutorial: http://api.gtkd.org/src/glib/Timeout.html#Timeout.add You may want to do something like this: ``` private void letButtonsFlash() { foreach(Button btn;bArr){ btn.setSensitive(false); } Timeout t = new Timeout(_delay,5,false); } private bool timeout_delay() { for(int i = 0; i < level; i++){ Button currentButton = bArr[rndButtonBlink[i]]; ListG list = currentButton.getStyleContext().listClasses(); string CSSClassName = to!string(cast(char*)list.next().data); currentButton.getStyleContext().addClass(CSSClassName ~ "-flash"); } return false; } ``` Thanks a lot for your answer, i tried it like this and it works: private void letButtonsFlash(){ foreach(Button btn;bArr){ btn.setSensitive(false); } for(int i = 0; i < level; i++){ Button currentButton = bArr[rndButtonBlink[i]]; ListG list = currentButton.getStyleContext().listClasses(); string CSSClassName = to!string(cast(char*)list.next().data); currentButton.getStyleContext().addClass(CSSClassName ~ "-flash"); } Timeout t = new Timeout(_delay,1,false); foreach(Button btn;bArr){ btn.setSensitive(true); } } bool timeout_delay(){ for(int i = 0; i < level; i++){ Button currentButton = bArr[rndButtonBlink[i]]; ListG list = currentButton.getStyleContext().listClasses(); string CSSClassName = to!string(cast(char*)list.next().data); currentButton.getStyleContext().removeClass(CSSClassName ~ "-flash"); } return false; } But i want to flash (e.g. change the CSS class) the buttons one by one and not all at the sime time? How am i going to do that?
Re: DbI checked integral
On Saturday, 25 June 2016 at 14:38:43 UTC, Robert burner Schadek wrote: I think there is a major problem with the proposed design. when Checked!(int, void) is to behave as an int, why do we need it in the first place. I mean we have int as a basic type. Can't we do: alias Int = int; alias Int = Checked!(int, SomeUsefulHook); On second thought, the only feature of Checked!(int, void) is to be a slower int ;-) IMO the default CheckedInt!(int, void) needs a NaN like init/failure state. After any operation that overflows the value should be NaN. IMO this is the same problem as for the test function with no arguments. What if your policy does nothing ? This is the end case, and while probably not very useful on its own, is very important to not push a ton of complexity on user code. Just like multiplying by 0 or 1 is not very useful, yet the MUL instruction and * operator accept these as operands. Like adding 0 is not useful, yet ADD and the + operator accept these as operand. It is important for library code to handle degenerate cases gracefully. Also I'd run the code in LLVM's opt to see what comes out, but I'd be pretty sure if we are careful, it can optimize everything away and get us back to ints.
Re: DbI checked integral
On 6/25/16 10:38 AM, Robert burner Schadek wrote: On Friday, 24 June 2016 at 21:31:14 UTC, Andrei Alexandrescu wrote: By default, if Hook has no state and implements none of these methods, e.g. is void, then Checked!(int, void) is a user-defined type that mimics the behavior of int to the maximum extent possible. I think there is a major problem with the proposed design. when Checked!(int, void) is to behave as an int, why do we need it in the first place. I mean we have int as a basic type. Can't we do: alias Int = int; alias Int = Checked!(int, SomeUsefulHook); On second thought, the only feature of Checked!(int, void) is to be a slower int ;-) Thanks for the feedback. There is at least one place in which built-in integrals are not entirely replaceable - literals. Consider: byte a = 0; short b = -1; ushort c = 1; All of the literals involved have type int, so in theory neither line should work. However, the compiler special-cases literals because it "knows" they are within bounds. This special casing is inaccessible to user-defined types. So it stands to reason that if you want to design a checked integral types offering a variety of checking policies, one point in the design space that needs to be attainable is "no checks at all". Then the syntactic shell works the same as with any policy, and ideally there's no overhead at all. IMO the default CheckedInt!(int, void) needs a NaN like init/failure state. After any operation that overflows the value should be NaN. One good design principle is pushing policy up and implementation down. A NaN is a very specific policy, which is appropriate for a Hook definition but would look out of place in the Checked shell. Andrei
Re: GTKD - CSS class color "flash" delay
On 06/25/2016 05:26 PM, TheDGuy wrote: On Saturday, 25 June 2016 at 13:01:09 UTC, TheDGuy wrote: Thanks for your answer. I have to pass the Button object to my timeout function to change the CSS class. But how do i do that within the Timeout constructor? I mean: I have to pass my function and delay time to the constructor, but i can't pass any data to the function here, also only functions are allowed (at least it looks like that to me) who don't have parameters. If i want to add a new function i have to use the function .add(), with this function i can pass 'userData' (so my button for example). But why am i unable to do that in the constructor? Do i have 2 different functions for the same thing, one with the other one without parameter? My current approach: private void letButtonsFlash(){ foreach(Button btn;bArr){ btn.setSensitive(false); } for(int i = 0; i < level; i++){ Button currentButton = bArr[rndButtonBlink[i]]; ListG list = currentButton.getStyleContext().listClasses(); string CSSClassName = to!string(cast(char*)list.next().data); currentButton.getStyleContext().addClass(CSSClassName ~ "-flash"); //writeln(CSSClassName); Timeout t = new Timeout(_delay,5,false); //error appears here t.add(5,_delay,currentButton); } foreach(Button btn;bArr){ btn.setSensitive(true); } } bool timeout_delay(Button currentButton){ ListG list = currentButton.getStyleContext().listClasses(); string CSSClassName = to!string(cast(char*)list.next().data); currentButton.getStyleContext().removeClass(CSSClassName ~ "-flash"); return false; } But i get the error: Error: none of the overloads of '__ctor' are callable using argument types (bool delegate(void* userData), int, bool), candidates are: glib.Timeout.Timeout.this(uint interval, bool delegate() dlg, bool fireNow = false) glib.Timeout.Timeout.this(uint interval, bool delegate() dlg, GPriority priority, bool fireNow = false) glib.Timeout.Timeout.this(bool delegate() dlg, uint seconds, bool fireNow = false) glib.Timeout.Timeout.this(bool delegate() dlg, uint seconds, GPriority priority, bool fireNow = false) If i take a look at GTK for C it looks like there is a function for that: http://www.gtk.org/tutorial1.2/gtk_tut-17.html Why is this so confusing? The constructor accepts an delegate, witch can access it's context so it has access to some of the data. The functions from GTK are also available like Timeout.add from the linked tutorial: http://api.gtkd.org/src/glib/Timeout.html#Timeout.add You may want to do something like this: ``` private void letButtonsFlash() { foreach(Button btn;bArr){ btn.setSensitive(false); } Timeout t = new Timeout(_delay,5,false); } private bool timeout_delay() { for(int i = 0; i < level; i++){ Button currentButton = bArr[rndButtonBlink[i]]; ListG list = currentButton.getStyleContext().listClasses(); string CSSClassName = to!string(cast(char*)list.next().data); currentButton.getStyleContext().addClass(CSSClassName ~ "-flash"); } return false; } ``` -- Mike Wey
Re: GSoC 2016 - std.experimental.xml after a month
On Saturday, 25 June 2016 at 20:32:33 UTC, Walter Bright wrote: Thank you for your hard work on this important project. Please ensure that it has a range interface - a range is used as input. You mean that the document source may be a range? In that case, I already implemented a lexer that works with any InputRange, and another one that works with ForwardRanges (I hoped it to be way faster than the first, but it currently isn't). Both are way slower than the two lexers based on slices, of course.
Re: GSoC 2016 - std.experimental.xml after a month
On Saturday, 25 June 2016 at 20:16:09 UTC, Steven Schveighoffer wrote: When I had the gumption to try and make an XML parser range, the idea I had was to have the current element's tag and attributes, all parent elements' tags and attributes, and the currently parsed entity inside the element. If the entity you were parsing was an element, you could either popFront it, to get to the next element, or descend into it's children, and the element and it's attributes would be pushed onto the "element" stack. The idea is to keep all the context alive, but not have to keep the entire file in memory. Anyway, that's how I envisioned it. Haven't finished my i/o package yet, so it didn't materialize :) -Steve Thank you for your feedback. You idea is similar to my Cursor API, which has next() to reach the next element and enter()/exit() to descend to the first child or ascend to the closing tag of the parent. But my implementation does not maintain the state of the parents, so you can't get any info about the parent from the children, unless you use exit() (in which case, you can get the parent's name from the closing tag). But your idea about a stack keeping all the context informations is quite valuable, given that some validations need them (e.g. checking that all prefixes have been declared, and retrieving prefix/namespace associations).
Re: GSoC 2016 - std.experimental.xml after a month
On 6/23/2016 1:04 PM, Lodovico Giaretta wrote: One month after the official GSoC start, I want to share with you what's in std.experimental.xml and what will hopefully be there Thank you for your hard work on this important project. Please ensure that it has a range interface - a range is used as input.
Re: GSoC 2016 - std.experimental.xml after a month
On 6/25/16 12:26 PM, Lodovico Giaretta wrote: On Saturday, 25 June 2016 at 15:59:40 UTC, Jacob Carlborg wrote: Any range API, or plan for? Hi, I'm definitely going to provide a wrapper around the Cursor API, that will provide InputRange access to all the children of the current node (this way the tree structure is maintained). I plan to upload it in a couple of days. I'm still pondering if it's worth providing also a way to get a Range of the entire document tree, flattened; it's nodes would be in one-to-one correspondence with the events generated by a SAX parser (another API which does not preserve the tree structure). When I had the gumption to try and make an XML parser range, the idea I had was to have the current element's tag and attributes, all parent elements' tags and attributes, and the currently parsed entity inside the element. If the entity you were parsing was an element, you could either popFront it, to get to the next element, or descend into it's children, and the element and it's attributes would be pushed onto the "element" stack. The idea is to keep all the context alive, but not have to keep the entire file in memory. Anyway, that's how I envisioned it. Haven't finished my i/o package yet, so it didn't materialize :) -Steve
[Issue 16202] Floating point types implicitly convert losing precision
https://issues.dlang.org/show_bug.cgi?id=16202 Steven Schveighofferchanged: What|Removed |Added CC||schvei...@yahoo.com --- Comment #3 from Steven Schveighoffer --- You are right, I can't find this explicitly stated anywhere. However, there is nothing that says it's not allowed, and all current implementations allow it. If we were to suddenly say "oh, actually, you can't do that", it would break too much code. So it's defacto part of the spec. This is still an enhancement. --
Re: static if enhancement
On Saturday, 25 June 2016 at 11:27:01 UTC, cym13 wrote: We are talking about early returns (checking for something and returning as soon as possible) which are a well-known and efficient way to reduce indentation levels and increase modularity. You can't come and say "What? You want it to work? Man, you should have thought your code better!": the very reason this subject is discussed is to allow people ...to think less. sorry.
[Issue 6278] Regression(2.054 beta): 'in' contract inheritance doesn't work with safe code
https://issues.dlang.org/show_bug.cgi?id=6278 --- Comment #15 from hst...@quickfur.ath.cx --- Shouldn't it be ContractError? --
Re: Project Highlight: The PowerNex Kernel
On Friday, 24 June 2016 at 15:09:41 UTC, Satoshi wrote: On Friday, 24 June 2016 at 14:09:12 UTC, Mike Parker wrote: Not that long ago, Dan Printzell announced his D OS Kernel, PowerNex [1], in this forum. It is now the subject of the first project highlight on the D Blog [2]. [1] https://github.com/Vild/PowerNex [2] http://dlang.org/blog/2016/06/24/project-highlight-the-powernex-kernel/ Its funny how he took existing sources from my OS https://github.com/Rikarin/Trinix rewrite it during stream session on Livecoding and get more popularity than my OS. Do you want me to remove all the code that is influenced by your code in the kernel and rewrite from scratch? Because I don't want my project to contain illegal/controversial code.
Re: Does D has any support for thunks?
On Saturday, 25 June 2016 at 17:26:03 UTC, Andre Pany wrote: On Saturday, 25 June 2016 at 16:05:30 UTC, Vladimir Panteleev wrote: On Saturday, 25 June 2016 at 13:44:48 UTC, Andre Pany wrote: Does D/Phobos has any support for thunks? Made this a while ago: http://stackoverflow.com/a/8656294/21501 Thanks, I had a look. Unfortunately it doesn't compile for my use case. SetWindowsHookEx expects an "extern(windows)" and "nothrow" function. delegate2function does not accept a delegate with If it is possible to make this coding generic, it would fit into std.functional. Kind regards André ... does not accept a delegate with extern(windows).
Re: Does D has any support for thunks?
On Saturday, 25 June 2016 at 16:05:30 UTC, Vladimir Panteleev wrote: On Saturday, 25 June 2016 at 13:44:48 UTC, Andre Pany wrote: Does D/Phobos has any support for thunks? Made this a while ago: http://stackoverflow.com/a/8656294/21501 Thanks, I had a look. Unfortunately it doesn't compile for my use case. SetWindowsHookEx expects an "extern(windows)" and "nothrow" function. delegate2function does not accept a delegate with If it is possible to make this coding generic, it would fit into std.functional. Kind regards André
Re: GSoC 2016 - std.experimental.xml after a month
On Saturday, 25 June 2016 at 15:59:40 UTC, Jacob Carlborg wrote: Any range API, or plan for? Hi, I'm definitely going to provide a wrapper around the Cursor API, that will provide InputRange access to all the children of the current node (this way the tree structure is maintained). I plan to upload it in a couple of days. I'm still pondering if it's worth providing also a way to get a Range of the entire document tree, flattened; it's nodes would be in one-to-one correspondence with the events generated by a SAX parser (another API which does not preserve the tree structure).
Re: pure D mpeg2 decoder
On Friday, 24 June 2016 at 07:35:51 UTC, Ruslan Mullakhmetov wrote: Hi all! I saw pure jpeg decoder was announced recently and I decided to publish pure D mpeg2 decoder that I wrote just for myself, with study aims. I didn't test it exhaustively, so don't judge me for bugs) Currently it supports only progressive sequences with no B frames. As for performance, it's 5 times slower than ffmpeg implementation, optimizations are required. link: https://github.com/theambient/mpeg2 Does someone want to write pure D AVC or HEVC decoder/encoder? =) P.S. It sometimes has some artifacts, I didn't try to fix them. Does it or do you plan to super decoding and and encoding programmatically (using built-in APIs)?
Re: Does D has any support for thunks?
On Saturday, 25 June 2016 at 13:44:48 UTC, Andre Pany wrote: Does D/Phobos has any support for thunks? Made this a while ago: http://stackoverflow.com/a/8656294/21501
Re: Optimizations and performance
On Friday, 17 June 2016 at 16:51:04 UTC, Jack Stouffer wrote: On Wednesday, 8 June 2016 at 22:19:47 UTC, Bauss wrote: D definitely needs some optimizations, I mean look at its benchmarks compared to other languages: https://github.com/kostya/benchmarks Welp, I tried making it faster and I apparently made it slower: https://github.com/kostya/benchmarks/pull/89 Oops. Fixed: https://github.com/kostya/benchmarks/pull/91 This should be enough to make D the fastest in bench.b and second/third after C++ Gcc / Crystal, without changing the algorithm, which is not allowed. Request to future contributors: please benchmark the code and make sure there's an improvement in the majority of compilers and most importantly in the fastest case (LDC in this instance) before submitting changes. Code style / refactoring changes are clearly welcome, as long as they don't decrease the performance. In this particular case `@safe` is a performance pessimization in release mode, because it introduces bounds checks. To remedy that, one has to compile with `-boundscheck=off`. See https://dlang.org/dmd-linux.html#switch-boundscheck for more info. A note about my changes: as for this piece of code we are only interested in performance and code brevity, I decided to omit attributes as no combination of them could bring performance improvement (and @safe was a pessimization in all of my tests, given the build flags). I have more information about the changes in the pull request. Overall DMD completes mandel.b for 75.5% of the time of the previous version, LDC for 62.6% and GDC for 88.1%. The code is 64.9% of the original (in terms of LOC).
Re: pure D mpeg2 decoder
On Friday, 24 June 2016 at 07:35:51 UTC, Ruslan Mullakhmetov wrote: Hi all! I saw pure jpeg decoder was announced recently and I decided to publish pure D mpeg2 decoder that I wrote just for myself, with study aims. I didn't test it exhaustively, so don't judge me for bugs) Currently it supports only progressive sequences with no B frames. As for performance, it's 5 times slower than ffmpeg implementation, optimizations are required. link: https://github.com/theambient/mpeg2 Does someone want to write pure D AVC or HEVC decoder/encoder? =) P.S. It sometimes has some artifacts, I didn't try to fix them. Video decoder and encoder will be really helpful to me :)
Re: GSoC 2016 - std.experimental.xml after a month
On 23/06/16 22:04, Lodovico Giaretta wrote: What is working? - Four lexers are provided to abstract different kinds of input from the other layers, providing different speed characteristics; - The parser splits the document into nodes, doing most of the hard work; - A cursor sits on top of the parser, providing an API to advance in the document and get information about the current node; it supports string interning, which can drastically lower memory consumption (given that most nodes share names and attributes); - A validating cursor is the same as a cursor, but allows the user to plug custom validators, that are executed while advancing in the input; in the future the library will provide some predefined validators to use with it; - A very simple SAX API built on top of the cursor API is the last thing added and tested; - A partial reimplementation of std.xml is there; when completed it will allow a gradual code transition. Any range API, or plan for? -- /Jacob Carlborg
Re: GTKD - CSS class color "flash" delay
On Saturday, 25 June 2016 at 15:26:00 UTC, TheDGuy wrote: } But i get the error: Error: none of the overloads of '__ctor' are callable using argument types (bool delegate(void* userData), int, bool), candidates are: This is the correct error message: Error: none of the overloads of '__ctor' are callable using argument types (bool delegate(Button currentButton), int, bool), candidates are:
Re: GTKD - CSS class color "flash" delay
On Saturday, 25 June 2016 at 13:01:09 UTC, TheDGuy wrote: Thanks for your answer. I have to pass the Button object to my timeout function to change the CSS class. But how do i do that within the Timeout constructor? I mean: I have to pass my function and delay time to the constructor, but i can't pass any data to the function here, also only functions are allowed (at least it looks like that to me) who don't have parameters. If i want to add a new function i have to use the function .add(), with this function i can pass 'userData' (so my button for example). But why am i unable to do that in the constructor? Do i have 2 different functions for the same thing, one with the other one without parameter? My current approach: private void letButtonsFlash(){ foreach(Button btn;bArr){ btn.setSensitive(false); } for(int i = 0; i < level; i++){ Button currentButton = bArr[rndButtonBlink[i]]; ListG list = currentButton.getStyleContext().listClasses(); string CSSClassName = to!string(cast(char*)list.next().data); currentButton.getStyleContext().addClass(CSSClassName ~ "-flash"); //writeln(CSSClassName); Timeout t = new Timeout(_delay,5,false); //error appears here t.add(5,_delay,currentButton); } foreach(Button btn;bArr){ btn.setSensitive(true); } } bool timeout_delay(Button currentButton){ ListG list = currentButton.getStyleContext().listClasses(); string CSSClassName = to!string(cast(char*)list.next().data); currentButton.getStyleContext().removeClass(CSSClassName ~ "-flash"); return false; } But i get the error: Error: none of the overloads of '__ctor' are callable using argument types (bool delegate(void* userData), int, bool), candidates are: glib.Timeout.Timeout.this(uint interval, bool delegate() dlg, bool fireNow = false) glib.Timeout.Timeout.this(uint interval, bool delegate() dlg, GPriority priority, bool fireNow = false) glib.Timeout.Timeout.this(bool delegate() dlg, uint seconds, bool fireNow = false) glib.Timeout.Timeout.this(bool delegate() dlg, uint seconds, GPriority priority, bool fireNow = false) If i take a look at GTK for C it looks like there is a function for that: http://www.gtk.org/tutorial1.2/gtk_tut-17.html Why is this so confusing?
Re: DbI checked integral
On Friday, 24 June 2016 at 21:31:14 UTC, Andrei Alexandrescu wrote: By default, if Hook has no state and implements none of these methods, e.g. is void, then Checked!(int, void) is a user-defined type that mimics the behavior of int to the maximum extent possible. I think there is a major problem with the proposed design. when Checked!(int, void) is to behave as an int, why do we need it in the first place. I mean we have int as a basic type. Can't we do: alias Int = int; alias Int = Checked!(int, SomeUsefulHook); On second thought, the only feature of Checked!(int, void) is to be a slower int ;-) IMO the default CheckedInt!(int, void) needs a NaN like init/failure state. After any operation that overflows the value should be NaN.
Re: static switch/pattern matching
On Saturday, 25 June 2016 at 12:35:39 UTC, Lodovico Giaretta wrote: On Saturday, 25 June 2016 at 12:30:22 UTC, Lodovico Giaretta wrote: If you want this to work, you need your lambdas to take the casted value as a parameter: Thanks.
Re: static if enhancement
On Saturday, 25 June 2016 at 10:19:47 UTC, Claude wrote: On Friday, 24 June 2016 at 15:24:48 UTC, Andrei Alexandrescu wrote: Does anyone else find this annoying? https://issues.dlang.org/show_bug.cgi?id=16201 -- Andrei My 2 cents. I don't find that annoying at all. It's perfectly normal IMHO. It may introduce an additional indentation level for the second part, but I reckon it is normal to have those 2 instruction blocks at the same level. If we were to introduce a new keyword for "static if else", why not do the same for the run-time "if else" (to be coherent)? And, if some code have too many indentation levels, than it probably means it should be better modularized, hence I'd suggest to split it in several sub-functions, it will be more readable/maintainable. I think if we want we could also add `if else` for run-time if too. In D we have wide usage of CT features and particularly `static if`. It becomes annoying and too verbose to write `else static if` when I have multiple branches, so I was thinking for some time to have `elif` keyword. In this case it would be enough to write static just one time at the beginning of `static if`. Compiler could understand that `elif` belongs to this exact `if` or `static if` that was before it.
Re: Does D has any support for thunks?
On Saturday, 25 June 2016 at 14:06:51 UTC, John wrote: On Saturday, 25 June 2016 at 13:44:48 UTC, Andre Pany wrote: [...] This will only work on X86: version(X86) struct FunctionPtr(TDelegate) if (is(TDelegate == delegate)) { [...] Thanks a lot John, that's fantastic. Kind regards André
Re: Does D has any support for thunks?
On Saturday, 25 June 2016 at 13:44:48 UTC, Andre Pany wrote: Hi everyone, I have some issue with win32 function SetWindowsHookEx. For this specific funtion there is no possibility to pass extra data (pointer to a class instance to be called) to the callback function. The general solution seems to use thunks. I found s.th. for c++: http://www.codeproject.com/Articles/16785/Thunking-in-Win-Simplifying-Callbacks-to-Non-sta Does D/Phobos has any support for thunks? Kind regards André This will only work on X86: version(X86) struct FunctionPtr(TDelegate) if (is(TDelegate == delegate)) { import std.traits; alias TResult = ReturnType!TDelegate; alias TParameters = Parameters!TDelegate; private struct ThunkCode { align(1): ubyte mov_eax; void* this_ptr; ubyte mov_ecx; void* func_ptr; ubyte mov_edx; void* cb_ptr; ushort jmp_edx; } this(TDelegate method) { this = method; } auto ref opAssign(TDelegate method) { extern(Windows) TResult callback(TParameters parameters) { TDelegate dg = void; asm { mov [dg], EAX; mov [dg + 4], ECX; } return dg(parameters); } if (auto thunk = cast(ThunkCode*)VirtualAlloc(null, ThunkCode.sizeof, MEM_COMMIT, PAGE_EXECUTE_READWRITE)) { with (thunk) { mov_eax = 0xB8; this_ptr = method.ptr; mov_ecx = 0xB9; func_ptr = method.funcptr; mov_edx = 0xBA; cb_ptr = jmp_edx = 0xE2FF; } FlushInstructionCache(GetCurrentProcess(), thunk, ThunkCode.sizeof); ptr = cast(typeof(ptr))thunk; } else { assert(false); } return this; } ~this() { if (ptr) { VirtualFree(ptr, ThunkCode.sizeof, MEM_DECOMMIT); ptr = null; } } extern(Windows) TResult function(TParameters) nothrow ptr; alias ptr this; } alias HookProc = FunctionPtr!(LRESULT delegate(int, WPARAM, LPARAM)); LRESULT hookProc(int code, WPARAM wparam, LPARAM lparam) { return 0; } HookProc hook = SetWindowsHookEx(WH_KEYBOARD, hook, GetModuleHandle(null), 0);
Re: Does D has any support for thunks?
On Saturday, 25 June 2016 at 13:44:48 UTC, Andre Pany wrote: Does D/Phobos has any support for thunks? It isn't included in the stdlib, but you can use the same C++ they describe in the link in D.
Does D has any support for thunks?
Hi everyone, I have some issue with win32 function SetWindowsHookEx. For this specific funtion there is no possibility to pass extra data (pointer to a class instance to be called) to the callback function. The general solution seems to use thunks. I found s.th. for c++: http://www.codeproject.com/Articles/16785/Thunking-in-Win-Simplifying-Callbacks-to-Non-sta Does D/Phobos has any support for thunks? Kind regards André
Re: GTKD - CSS class color "flash" delay
On Saturday, 25 June 2016 at 11:45:40 UTC, Mike Wey wrote: You should change the css class in the timeout_delay function. It's called by the GTK main loop every time the amount of seconds passed to the constructor has passed. And return true if you want to continue to flash the button, and false to stop. Also don't sleep in the timeout function, the main loop should take care of that, currently you are blocking the main thread for 5 seconds. Thanks for your answer. I have to pass the Button object to my timeout function to change the CSS class. But how do i do that within the Timeout constructor?
Re: static switch/pattern matching
On Saturday, 25 June 2016 at 12:30:22 UTC, Lodovico Giaretta wrote: If you want this to work, you need your lambdas to take the casted value as a parameter: void test(T)(T value) { int i; string s; match!(value, int, (val) => i = val, string, (val) => s = val ); } And of course you need to modify match! for this to work. Something like this: void match(alias t, cases...)() { static if (cases.length == 1) cases[0](); else static if (cases.length > 2) { static if (is(typeof(cases[0]) == bool)) { static if (cases[0]) cases[1](t); else match!(t, cases[2 .. $]); } else static if (is(typeof(t) == cases[0])) cases[1](t); else match!(t, cases[2 .. $]); } } void test(T)(T value) { int i; string s; match!(value, int, (val) => i = val, string, (val) => s = val ); } void main() { test(1); test("A string"); }
Re: Fiber local GC
On Saturday, 25 June 2016 at 10:49:43 UTC, qznc wrote: Since fibers are bound to a thread, a thread-local GC would help as well. The hard part is how to make it safe. Yes, but a thread is usually long-lived, so you don't get the free-all-no-collection-needed speedup. I don't think it is so hard to make it safe, but we need to get rid of the idea that it is inconvenient to use a more complex type system for pointers. I don't really see why that is a big issue, as type-erasure before code-gen would prevent bloat. I think it is neither easy or hard to make it safe. It is doable, if we make the right trade-offs. But more advanced typing of pointers is most likely needed.
Re: static switch/pattern matching
On Saturday, 25 June 2016 at 10:39:09 UTC, John wrote: Thanks for the help, both. This appeared to work, until I realised the lambda isn't static: void match(T, cases...)() { static if (cases.length == 1) cases[0](); else static if (cases.length > 2) { static if (is(typeof(cases[0]) == bool)) { static if (cases[0]) cases[1](); else match!(T, cases[2 .. $]); } else static if (is(T == cases[0])) cases[1](); else match!(T, cases[2 .. $]); } } void test(T)(T value) { int i; string s; match!(T, int, () => i = value, string, () => s = value ); } test(1); test("A string"); The compiler complains about not being able convert an int to a string and vice versa. If you want this to work, you need your lambdas to take the casted value as a parameter: void test(T)(T value) { int i; string s; match!(value, int, (val) => i = val, string, (val) => s = val ); } And of course you need to modify match! for this to work.
Re: Project Highlight: The PowerNex Kernel
On Friday, 24 June 2016 at 21:36:27 UTC, Wild wrote: On Friday, 24 June 2016 at 14:11:43 UTC, Mike Parker wrote: On Friday, 24 June 2016 at 14:09:12 UTC, Mike Parker wrote: Not that long ago, Dan Printzell announced his D OS Kernel, PowerNex [1], in this forum. It is now the subject of the first project highlight on the D Blog [2]. [1] https://github.com/Vild/PowerNex [2] http://dlang.org/blog/2016/06/24/project-highlight-the-powernex-kernel/ And the reddit thread is here: https://www.reddit.com/r/programming/comments/4pn19m/from_the_d_blog_project_highlight_the_powernex/ Someone posted it to Hacker News: https://news.ycombinator.com/item?id=11969891 Also on Phoronix: http://phoronix.com/scan.php?page=news_item=PowerNex-D-Lang Congrats :)
Re: Fiber local GC
On Saturday, 25 June 2016 at 12:01:25 UTC, rikki cattermole wrote: 2. You can hand out borrowed fiber-references to the fiber heap when calling non-fiber functions, but fiber-references can never be turned into non-fiber references. This worries me. 1. This adds ref counting or some other form of restriction which has not been declared as to what it is. You can get quite far using modern type systems and static analysis. You don't need to reference count, unless you export the object outside the fiber. Or rather, the reference count is only increased outside the fiber, if it is not reference outside the fiber it stays at 0 (conceptually). 2. Removes the ability to assign to globals limiting usage. You can add weak-references. Pin the object as being weakly referenced. When the weak reference is accessed (using RAII), and the object is alive, a weak-reference-counter is increased, when the access is over (RAII goes out of scope) the weak-reference-counter is decreased. If the object no longer exists you get either null or an exception.
Re: Fiber local GC
On 25/06/2016 11:55 PM, Ola Fosheim Grøstad wrote: On Saturday, 25 June 2016 at 11:37:44 UTC, rikki cattermole wrote: I've thought about this further, the only hook function we don't currently have is related to global + TLS assignment for memory. We can get away with e.g. new overriding and ~ via the GC proxy (actually a fairly decent way to go about it). Since this assignment hook is potentially quite expensive, it definitely should be only if used under whatever attribute we use. I think the basic idea would be that the fiber heap is presumed to work like a region allocator that is never collected, except when you run low on memory, then you scan only the fiber-local memory (and since it is local you could possibly also compact). So: 1. References to the fiber heap can only be made from the same fiber heap or the fiber stack. 2. You can hand out borrowed fiber-references to the fiber heap when calling non-fiber functions, but fiber-references can never be turned into non-fiber references. This worries me. 1. This adds ref counting or some other form of restriction which has not been declared as to what it is. 2. Removes the ability to assign to globals limiting usage. 3. Aggregates (structs/classes/arrays) that can contain fiber-references are tainted as fiber-local and cannot leave the fiber. Then you need a mechanism that transitively converts fiber-local data into non-fiber-local data. This can be done as either: 1. Deep copy. 2. Traverse-and-pin-memory-as-exported, then reinterpret cast into non-fiber-local types. 3. Optimization: a priori detected as non-fiber-local using static analysis and allocated in a separate heap and then reinterpret casted into non-fiber-local before being exported outside the fiber. Memory outside the fiber can use regular reference-counting. Of course, this could also be generalized to something that would not only work for fibers, but also for stack-less contexts such as a facade to a global graph that is only collectible at specific points in the code. So you collect only where there are no external references to internal nodes (or use reference-counted pinning for exports). A fiber-local heap would be a special case where the fiber-stack is part of the fiber-local heap. I think this might work. The assumption is that GC is most useful in a singular execution context and that more manual management (like reference counting) is acceptable between execution contexts.
Re: Fiber local GC
On Saturday, 25 June 2016 at 11:37:44 UTC, rikki cattermole wrote: I've thought about this further, the only hook function we don't currently have is related to global + TLS assignment for memory. We can get away with e.g. new overriding and ~ via the GC proxy (actually a fairly decent way to go about it). Since this assignment hook is potentially quite expensive, it definitely should be only if used under whatever attribute we use. I think the basic idea would be that the fiber heap is presumed to work like a region allocator that is never collected, except when you run low on memory, then you scan only the fiber-local memory (and since it is local you could possibly also compact). So: 1. References to the fiber heap can only be made from the same fiber heap or the fiber stack. 2. You can hand out borrowed fiber-references to the fiber heap when calling non-fiber functions, but fiber-references can never be turned into non-fiber references. 3. Aggregates (structs/classes/arrays) that can contain fiber-references are tainted as fiber-local and cannot leave the fiber. Then you need a mechanism that transitively converts fiber-local data into non-fiber-local data. This can be done as either: 1. Deep copy. 2. Traverse-and-pin-memory-as-exported, then reinterpret cast into non-fiber-local types. 3. Optimization: a priori detected as non-fiber-local using static analysis and allocated in a separate heap and then reinterpret casted into non-fiber-local before being exported outside the fiber. Memory outside the fiber can use regular reference-counting. Of course, this could also be generalized to something that would not only work for fibers, but also for stack-less contexts such as a facade to a global graph that is only collectible at specific points in the code. So you collect only where there are no external references to internal nodes (or use reference-counted pinning for exports). A fiber-local heap would be a special case where the fiber-stack is part of the fiber-local heap. I think this might work. The assumption is that GC is most useful in a singular execution context and that more manual management (like reference counting) is acceptable between execution contexts.
Re: GTKD - CSS class color "flash" delay
On 06/24/2016 10:03 PM, TheDGuy wrote: On Friday, 24 June 2016 at 16:44:59 UTC, Gerald wrote: Other then the obvious multi-threaded, using glib.Timeout to trigger the reversion of the color change could be an option. http://api.gtkd.org/src/glib/Timeout.html Thanks! I tried this so far: private void letButtonsFlash(){ foreach(Button btn;bArr){ btn.setSensitive(false); } for(int i = 0; i < level; i++){ Button currentButton = bArr[rndButtonBlink[i]]; ListG list = currentButton.getStyleContext().listClasses(); string CSSClassName = to!string(cast(char*)list.next().data); currentButton.getStyleContext().addClass(CSSClassName ~ "-flash"); writeln(CSSClassName); Timeout t = new Timeout(_delay,1,true); currentButton.getStyleContext().removeClass(CSSClassName ~ "-flash"); } foreach(Button btn;bArr){ btn.setSensitive(true); } } bool timeout_delay(){ Thread.sleep(dur!("seconds")(5)); return false; } and it is "working" to the extend that at least the CSSClassName gets written in the console but the UI again just pops up after 5 sec. Could you give me a tip? You should change the css class in the timeout_delay function. It's called by the GTK main loop every time the amount of seconds passed to the constructor has passed. And return true if you want to continue to flash the button, and false to stop. Also don't sleep in the timeout function, the main loop should take care of that, currently you are blocking the main thread for 5 seconds. -- Mike Wey
Re: Fiber local GC
On 25/06/2016 11:00 PM, rikki cattermole wrote: ... snip ... What we want is to be able to explicitly say what the context is for a functions code and declare no globals. @noglobals struct MyContext { @disable this(this); void func() { } } Function calls outside of the struct are ok for: @system, pure and @noglobals. Making the struct pure wouldn't work since there goes @safe and @system calls. MyContext.func would implicitly have @noglobals applied to it. Now preferably we would have new hooks added so they could be in the context. Specifically if they are there they are used instead of the globals for e.g. GC. That way things like allocators could be used instead. Given that the context should be heap/stack allocated and never copied it would mean that once the fiber dies, all memory it uses is deallocated or returned to the pool. Now I did say about hooks, there are no ways to do that without having a bunch of context pointers somewhere saying which function is currently set to the hook. If done via a stack it would given history for unsetting the current context allowing recursive. The underlying fiber provider would have to inform the switch on e.g. yield. But that isn't hard to do. Looking back perhaps we can allow globals, but we'd need to instead have a hook for when assigning to a global / passing to anything not pure that is heap based. That would allow "moving" memory ownership from the fiber to the process GC. TLDR: I think we can do this with just a @noglobals attribute, but done properly it looks like we need proper hooks in place which are a lot harder. I've thought about this further, the only hook function we don't currently have is related to global + TLS assignment for memory. We can get away with e.g. new overriding and ~ via the GC proxy (actually a fairly decent way to go about it). Since this assignment hook is potentially quite expensive, it definitely should be only if used under whatever attribute we use.
Re: static if enhancement
On Saturday, 25 June 2016 at 10:19:47 UTC, Claude wrote: And if some code have too many indentation levels, than it probably means it should be better modularized, hence I'd suggest to split it in several sub-functions, it will be more readable/maintainable. We are talking about early returns (checking for something and returning as soon as possible) which are a well-known and efficient way to reduce indentation levels and increase modularity. You can't come and say "What? You want it to work? Man, you should have thought your code better!": the very reason this subject is discussed is to allow people to deal with indentation levels!
Re: Fiber local GC
On 25/06/2016 10:33 PM, Ola Fosheim Grøstad wrote: Pony has a fiber local GC, which means collection can happen when the fiber is inactive or even altogether skip collection if the fiber is short-lived. Go is currently exploring a Transaction Oriented GC addition to the concurrent GC it already has: https://docs.google.com/document/d/1gCsFxXamW8RRvOe5hECz98Ftk-tcRRJcDFANj2VwCB0/edit It takes the same viewpoint. A go-routine (fiber) that is short-lived (like a HTTP request handler) can release everything in one swipe without collection. I think this viewpoint is much more efficient and promising than D's thread-local viewpoint. What D needs is a type qualifier that keeps data "fiber local" and possibly a transition mechanism like Pony has for detecting objects that should be allocated on a global heap (or less efficiently, "pin objects" that are exported outside the fiber). No need for a new keyword. What we could do is use a type like Vibe.d's TalkLocal to limit instances to the thread and register a context via a template for the struct describing the context. struct MyContext { int x; string text; } TaskLocal!MyContext context; shared static this() { registerFiberLocal(); } ... registerFiberLocal(T)(T* inst) if (is(T == struct)) { ... } Hmm okay maybe not a good idea. As a library like this won't work. What we want is to be able to explicitly say what the context is for a functions code and declare no globals. @noglobals struct MyContext { @disable this(this); void func() { } } Function calls outside of the struct are ok for: @system, pure and @noglobals. Making the struct pure wouldn't work since there goes @safe and @system calls. MyContext.func would implicitly have @noglobals applied to it. Now preferably we would have new hooks added so they could be in the context. Specifically if they are there they are used instead of the globals for e.g. GC. That way things like allocators could be used instead. Given that the context should be heap/stack allocated and never copied it would mean that once the fiber dies, all memory it uses is deallocated or returned to the pool. Now I did say about hooks, there are no ways to do that without having a bunch of context pointers somewhere saying which function is currently set to the hook. If done via a stack it would given history for unsetting the current context allowing recursive. The underlying fiber provider would have to inform the switch on e.g. yield. But that isn't hard to do. Looking back perhaps we can allow globals, but we'd need to instead have a hook for when assigning to a global / passing to anything not pure that is heap based. That would allow "moving" memory ownership from the fiber to the process GC. TLDR: I think we can do this with just a @noglobals attribute, but done properly it looks like we need proper hooks in place which are a lot harder.
Re: When using the -profile flag is it known behaviour that phobos unit tests fail?
On 6/25/2016 12:52 AM, Gary Willoughby wrote: Done. Good!
Re: Fiber local GC
On Saturday, 25 June 2016 at 10:33:00 UTC, Ola Fosheim Grøstad wrote: Pony has a fiber local GC, which means collection can happen when the fiber is inactive or even altogether skip collection if the fiber is short-lived. Go is currently exploring a Transaction Oriented GC addition to the concurrent GC it already has: https://docs.google.com/document/d/1gCsFxXamW8RRvOe5hECz98Ftk-tcRRJcDFANj2VwCB0/edit It takes the same viewpoint. A go-routine (fiber) that is short-lived (like a HTTP request handler) can release everything in one swipe without collection. I think this viewpoint is much more efficient and promising than D's thread-local viewpoint. What D needs is a type qualifier that keeps data "fiber local" and possibly a transition mechanism like Pony has for detecting objects that should be allocated on a global heap (or less efficiently, "pin objects" that are exported outside the fiber). D does not even have thread-local GC. Since fibers are bound to a thread, a thread-local GC would help as well. The hard part is how to make it safe.
Re: Is there a dmd.exe x86_64 out there?
On 25/06/2016 10:25 PM, Dlangofile wrote: On Saturday, 25 June 2016 at 09:39:21 UTC, rikki cattermole wrote: On 25/06/2016 9:03 PM, Dlangofile wrote: On Saturday, 25 June 2016 at 03:29:02 UTC, rikki cattermole wrote: On 25/06/2016 5:57 AM, Dlangofile wrote: Hi all, I'm building a Docker Alpine linux image with wine, for being able to forge Windows executable from my laptop, without having to dual boot. With my disappointment, I'm not able to run 32bit executable from the container right now, so the easy way is running a win64 dmd.exe: someone can point me to a pre-build executable, based on the latest version? Thanks Umm, x86_64 is backwards compatible with x86. So if 32bit build of dmd doesn't work, you have bigger problems. Well, frankly speaking I don't know! PE32+ executable (console) x86-64, for MS Windows -> working well PE32 executable (console) Intel 80386, for MS Windows -> not working at all I tried also to use a WINEARCH=win32, without success: I'm attaching the Dockerfile at the end, if someone wants to help more on that. In the meantime, any x86-64 DMD executable? What's the problem in having it available by default in the Windows distribution? Thanks /D FROM alpine:3.4 RUN apk --no-cache add wine freetype ncurses file ENV WINEARCH=win64 RUN wineboot ADD dmd2 /dmd2 CMD ["sh"] We need to see any errors produced from Wine. It is known that dmd does run under it. Which means something is wrong with your setup. with WINEARCH=win64 /dmd2/windows/bin # wineconsole dmd.exe err:winediag:nulldrv_CreateWindow Application tried to create a window, but no driver could be loaded. err:winediag:nulldrv_CreateWindow Make sure that your X server is running and that $DISPLAY is set correctly. wineconsole: Starting program "dmd.exe" failed. The command is invalid. with WINEARCH=win32 /dmd2/windows/bin # wineconsole dmd.exe wine: '/root/.wine' is a 32-bit installation, it cannot support 64-bit applications. As I said about x86_64 being backwards compatible with x86 (you can even run old 386 programs on a modern day cpu, go figure) so that isn't the problem. Maybe the Alpine Linux package for Wine has only 64-bit support... Maybe, Linux is finicky here library wise. Usually both arch binaries are required library wise and since Alpine is minimal.. easy to assume. The reason why we do not provide a dmd compiled for 64bit is simply, 32bit works in pretty much all cases. The cases it doesn't involve very large code bases being compiled. I understand, but what's exactly the problem in providing a 64bit version of the executable? Not providing it has just complicated my experience with D... :-) You're the first in over six months to bring up this issue, so not a common requirement ;) I just had a look into Wine, I'm not sure if this helps[0]. Right now you're not creating a new Wine environment or configuring it. I think that the 'wineboot' command in the Dockerfile just do it: I can run Win64 console application... Based on what I read, wineboot handles an instance lifetime e.g. restart. So killing of processes and getting mounts in for example. The link I gave has an example of a program that configures a new instance of Wine that is 32bit (since you can't change a 64bit one to 32bit) which is not the same thing. Otherwise, can you change over to a 32bit image instead of 64bit alpine? That probably will also fix it. Probably yes, maybe with an Ubuntu image as a base. The point is that everyone in docker is switching to Alpine distributions, as an alpine based image is far smaller that the other options, and the official Docker image of Alpine is 64bit only Given this information, yeah it might be worthwhile to distribute a build of dmd that is 64bit for Windows. But this won't allow you to execute the produced programs under Wine. Since you can't execute 32bit programs and since you can't really install MSVC or the required programs/libraries from Microsoft your stuck there. So really you want to get this sorted out.
Re: static switch/pattern matching
On Saturday, 25 June 2016 at 09:12:12 UTC, Lodovico Giaretta wrote: On Saturday, 25 June 2016 at 09:07:19 UTC, Lodovico Giaretta wrote: Instead of passing functions to match!, pass pairs of arguments, like this: match!(T, int, writeln("Matched int"), is(T : SomeObject), writeln("Derives from SomeObject"); ); Now, in the implementation, foreach pair of arguments, if the first member is a type that matches your target, perform that branch; otherwise, if the first member is a boolean value, and it is true, perform the branch. Of course I meant: match!(T, int, () {writeln("Matched int");}, is(T : SomeObject), () {writeln("Derives from SomeObject");} ); Thanks for the help, both. This appeared to work, until I realised the lambda isn't static: void match(T, cases...)() { static if (cases.length == 1) cases[0](); else static if (cases.length > 2) { static if (is(typeof(cases[0]) == bool)) { static if (cases[0]) cases[1](); else match!(T, cases[2 .. $]); } else static if (is(T == cases[0])) cases[1](); else match!(T, cases[2 .. $]); } } void test(T)(T value) { int i; string s; match!(T, int, () => i = value, string, () => s = value ); } test(1); test("A string"); The compiler complains about not being able convert an int to a string and vice versa.
Fiber local GC
Pony has a fiber local GC, which means collection can happen when the fiber is inactive or even altogether skip collection if the fiber is short-lived. Go is currently exploring a Transaction Oriented GC addition to the concurrent GC it already has: https://docs.google.com/document/d/1gCsFxXamW8RRvOe5hECz98Ftk-tcRRJcDFANj2VwCB0/edit It takes the same viewpoint. A go-routine (fiber) that is short-lived (like a HTTP request handler) can release everything in one swipe without collection. I think this viewpoint is much more efficient and promising than D's thread-local viewpoint. What D needs is a type qualifier that keeps data "fiber local" and possibly a transition mechanism like Pony has for detecting objects that should be allocated on a global heap (or less efficiently, "pin objects" that are exported outside the fiber).
Re: Is there a dmd.exe x86_64 out there?
On Saturday, 25 June 2016 at 09:39:21 UTC, rikki cattermole wrote: On 25/06/2016 9:03 PM, Dlangofile wrote: On Saturday, 25 June 2016 at 03:29:02 UTC, rikki cattermole wrote: On 25/06/2016 5:57 AM, Dlangofile wrote: Hi all, I'm building a Docker Alpine linux image with wine, for being able to forge Windows executable from my laptop, without having to dual boot. With my disappointment, I'm not able to run 32bit executable from the container right now, so the easy way is running a win64 dmd.exe: someone can point me to a pre-build executable, based on the latest version? Thanks Umm, x86_64 is backwards compatible with x86. So if 32bit build of dmd doesn't work, you have bigger problems. Well, frankly speaking I don't know! PE32+ executable (console) x86-64, for MS Windows -> working well PE32 executable (console) Intel 80386, for MS Windows -> not working at all I tried also to use a WINEARCH=win32, without success: I'm attaching the Dockerfile at the end, if someone wants to help more on that. In the meantime, any x86-64 DMD executable? What's the problem in having it available by default in the Windows distribution? Thanks /D FROM alpine:3.4 RUN apk --no-cache add wine freetype ncurses file ENV WINEARCH=win64 RUN wineboot ADD dmd2 /dmd2 CMD ["sh"] We need to see any errors produced from Wine. It is known that dmd does run under it. Which means something is wrong with your setup. with WINEARCH=win64 /dmd2/windows/bin # wineconsole dmd.exe err:winediag:nulldrv_CreateWindow Application tried to create a window, but no driver could be loaded. err:winediag:nulldrv_CreateWindow Make sure that your X server is running and that $DISPLAY is set correctly. wineconsole: Starting program "dmd.exe" failed. The command is invalid. with WINEARCH=win32 /dmd2/windows/bin # wineconsole dmd.exe wine: '/root/.wine' is a 32-bit installation, it cannot support 64-bit applications. As I said about x86_64 being backwards compatible with x86 (you can even run old 386 programs on a modern day cpu, go figure) so that isn't the problem. Maybe the Alpine Linux package for Wine has only 64-bit support... The reason why we do not provide a dmd compiled for 64bit is simply, 32bit works in pretty much all cases. The cases it doesn't involve very large code bases being compiled. I understand, but what's exactly the problem in providing a 64bit version of the executable? Not providing it has just complicated my experience with D... :-) I just had a look into Wine, I'm not sure if this helps[0]. Right now you're not creating a new Wine environment or configuring it. I think that the 'wineboot' command in the Dockerfile just do it: I can run Win64 console application... Otherwise, can you change over to a 32bit image instead of 64bit alpine? That probably will also fix it. Probably yes, maybe with an Ubuntu image as a base. The point is that everyone in docker is switching to Alpine distributions, as an alpine based image is far smaller that the other options, and the official Docker image of Alpine is 64bit only
Re: static if enhancement
On Friday, 24 June 2016 at 15:24:48 UTC, Andrei Alexandrescu wrote: Does anyone else find this annoying? https://issues.dlang.org/show_bug.cgi?id=16201 -- Andrei My 2 cents. I don't find that annoying at all. It's perfectly normal IMHO. It may introduce an additional indentation level for the second part, but I reckon it is normal to have those 2 instruction blocks at the same level. If we were to introduce a new keyword for "static if else", why not do the same for the run-time "if else" (to be coherent)? And, if some code have too many indentation levels, than it probably means it should be better modularized, hence I'd suggest to split it in several sub-functions, it will be more readable/maintainable.
Re: Is there a dmd.exe x86_64 out there?
On 25/06/2016 9:03 PM, Dlangofile wrote: On Saturday, 25 June 2016 at 03:29:02 UTC, rikki cattermole wrote: On 25/06/2016 5:57 AM, Dlangofile wrote: Hi all, I'm building a Docker Alpine linux image with wine, for being able to forge Windows executable from my laptop, without having to dual boot. With my disappointment, I'm not able to run 32bit executable from the container right now, so the easy way is running a win64 dmd.exe: someone can point me to a pre-build executable, based on the latest version? Thanks Umm, x86_64 is backwards compatible with x86. So if 32bit build of dmd doesn't work, you have bigger problems. Well, frankly speaking I don't know! PE32+ executable (console) x86-64, for MS Windows -> working well PE32 executable (console) Intel 80386, for MS Windows -> not working at all I tried also to use a WINEARCH=win32, without success: I'm attaching the Dockerfile at the end, if someone wants to help more on that. In the meantime, any x86-64 DMD executable? What's the problem in having it available by default in the Windows distribution? Thanks /D FROM alpine:3.4 RUN apk --no-cache add wine freetype ncurses file ENV WINEARCH=win64 RUN wineboot ADD dmd2 /dmd2 CMD ["sh"] We need to see any errors produced from Wine. It is known that dmd does run under it. Which means something is wrong with your setup. As I said about x86_64 being backwards compatible with x86 (you can even run old 386 programs on a modern day cpu, go figure) so that isn't the problem. The reason why we do not provide a dmd compiled for 64bit is simply, 32bit works in pretty much all cases. The cases it doesn't involve very large code bases being compiled. The only platform this may not be true for is OSX where 32bit is long dead globally and 64bit is the only option. Sadly Windows and Linux still have 32bit cpus common in the last 10 years. I just had a look into Wine, I'm not sure if this helps[0]. Right now you're not creating a new Wine environment or configuring it. Otherwise, can you change over to a 32bit image instead of 64bit alpine? That probably will also fix it. [0] https://wiki.winehq.org/FAQ#How_do_I_create_a_32_bit_wineprefix_on_a_64_bit_system.3F
Re: static switch/pattern matching
On Saturday, 25 June 2016 at 09:07:19 UTC, Lodovico Giaretta wrote: Instead of passing functions to match!, pass pairs of arguments, like this: match!(T, int, writeln("Matched int"), is(T : SomeObject), writeln("Derives from SomeObject"); ); Now, in the implementation, foreach pair of arguments, if the first member is a type that matches your target, perform that branch; otherwise, if the first member is a boolean value, and it is true, perform the branch. Of course I meant: match!(T, int, () {writeln("Matched int");}, is(T : SomeObject), () {writeln("Derives from SomeObject");} ); You could probably even match on the actual value (instead of its type) and pass it (correctly casted) to the functions: match!(t, int, (int t) {writeln("Matched int ", t);}, is(T : SomeObject), (SomeObject t) {writeln(t, " derives from SomeObject");} ); I don't have time to implement it now, but I think it's not too difficult.
Re: static switch/pattern matching
also, there is a subtle bug in matcher. sorry. ;-)
Re: static switch/pattern matching
On Saturday, 25 June 2016 at 08:46:05 UTC, John wrote: Anyone able to improve on it? q hack: template tyma(T, Cases...) { import std.traits; template GetFunc(size_t idx) { static if (idx >= Cases.length) { static assert(0, "no delegate for match"); } else static if (isCallable!(Cases[idx])) { enum GetFunc = Cases[idx]; } else { enum GetFunc = GetFunc!(idx+1); } } template Matcher(size_t idx) { //pragma(msg, "T=", T, "; idx=", idx, "; Cases[idx]=", Cases[idx], "; is=", is(typeof(T) == Cases[idx])); static if (idx >= Cases.length) { static assert(0, "no match, consider adding `void` branch"); } else static if (isCallable!(Cases[idx])) { enum Matcher = Matcher!(idx+1); } else static if (is(Cases[idx] == void)) { enum Matcher = GetFunc!(idx+1); } else static if (is(typeof(Cases[idx]) == string)) { mixin("static if (is(T:"~Cases[idx]~")) enum Matcher = GetFunc!(idx+1); else enum Matcher = Matcher!(idx+1);"); } else static if (is(typeof(Cases[idx]))) { static assert(0, "unexpected something in cases: "~Cases[idx].stringof); } else static if (is(T == Cases[idx])) { enum Matcher = GetFunc!(idx+1); } else { enum Matcher = Matcher!(idx+1); } } enum tyma = Matcher!0; } void main () { import std.stdio; auto res = tyma!(int, string, () => "string", "long", () => "integral", void, () => "anything", )(); writeln(res); } note that you should separate type names from labdas with "," instead of doing `int => "integral`, and have to add `()` at the end to actually call the delegate.
Re: static switch/pattern matching
On Saturday, 25 June 2016 at 08:46:05 UTC, John wrote: Writing a long series of "static if ... else" statements can be tedious and I'm prone to leaving out the crucial "static" after "else", so I was wondered if it was possible to write a template that would resemble the switch statement, but for types. Closest I came up to was this: void match(T, Fs...)() { foreach (F; Fs) { static if (isFunctionPointer!F) { alias Ps = Parameters!F; static if (Ps.length == 1) { static if (is(Ps[0] == T)) F(Ps[0].init); } } } } void test(T)(T t) { match!(T, (int _) => writeln("Matched int"), (string _) => writeln("Matched string") ); } But that's pretty limited and I'd like to be able to match on whether a type derives from T as well. I just can't figure it out. Something like this would be ideal... match!(T, int => writeln("Matched int"), is(T : SomeObject) => writeln("Derives from SomeObject") ); Anyone able to improve on it? Instead of passing functions to match!, pass pairs of arguments, like this: match!(T, int, writeln("Matched int"), is(T : SomeObject), writeln("Derives from SomeObject"); ); Now, in the implementation, foreach pair of arguments, if the first member is a type that matches your target, perform that branch; otherwise, if the first member is a boolean value, and it is true, perform the branch.
Re: Is there a dmd.exe x86_64 out there?
On Saturday, 25 June 2016 at 03:29:02 UTC, rikki cattermole wrote: On 25/06/2016 5:57 AM, Dlangofile wrote: Hi all, I'm building a Docker Alpine linux image with wine, for being able to forge Windows executable from my laptop, without having to dual boot. With my disappointment, I'm not able to run 32bit executable from the container right now, so the easy way is running a win64 dmd.exe: someone can point me to a pre-build executable, based on the latest version? Thanks Umm, x86_64 is backwards compatible with x86. So if 32bit build of dmd doesn't work, you have bigger problems. Well, frankly speaking I don't know! PE32+ executable (console) x86-64, for MS Windows -> working well PE32 executable (console) Intel 80386, for MS Windows -> not working at all I tried also to use a WINEARCH=win32, without success: I'm attaching the Dockerfile at the end, if someone wants to help more on that. In the meantime, any x86-64 DMD executable? What's the problem in having it available by default in the Windows distribution? Thanks /D FROM alpine:3.4 RUN apk --no-cache add wine freetype ncurses file ENV WINEARCH=win64 RUN wineboot ADD dmd2 /dmd2 CMD ["sh"]
static switch/pattern matching
Writing a long series of "static if ... else" statements can be tedious and I'm prone to leaving out the crucial "static" after "else", so I was wondered if it was possible to write a template that would resemble the switch statement, but for types. Closest I came up to was this: void match(T, Fs...)() { foreach (F; Fs) { static if (isFunctionPointer!F) { alias Ps = Parameters!F; static if (Ps.length == 1) { static if (is(Ps[0] == T)) F(Ps[0].init); } } } } void test(T)(T t) { match!(T, (int _) => writeln("Matched int"), (string _) => writeln("Matched string") ); } But that's pretty limited and I'd like to be able to match on whether a type derives from T as well. I just can't figure it out. Something like this would be ideal... match!(T, int => writeln("Matched int"), is(T : SomeObject) => writeln("Derives from SomeObject") ); Anyone able to improve on it?
Re: When using the -profile flag is it known behaviour that phobos unit tests fail?
On Friday, 24 June 2016 at 22:24:09 UTC, Walter Bright wrote: Please post bug reports to bugzilla. They'll get lost in the n.g. Done. https://issues.dlang.org/show_bug.cgi?id=16204
[Issue 16204] New: When using the -profile flag phobos unit tests fail
https://issues.dlang.org/show_bug.cgi?id=16204 Issue ID: 16204 Summary: When using the -profile flag phobos unit tests fail Product: D Version: D2 Hardware: x86_64 OS: Linux Status: NEW Severity: normal Priority: P1 Component: phobos Assignee: nob...@puremagic.com Reporter: d...@nomad.so When using the -profile flag phobos unit tests fail (Ubuntu 16.04 - DMD64 D Compiler v2.071.0) For example, when following these steps I get a failed unit test: $ cd /usr/include/dmd/phobos/std/ $ rdmd --force -I/usr/include/dmd/phobos/std -I/usr/include/dmd/phobos/core -main -unittest -profile format.d Without the -profile flag it works. I only tried the format module, others may be affected. --
Re: static if enhancement
On Friday, 24 June 2016 at 15:24:48 UTC, Andrei Alexandrescu wrote: Does anyone else find this annoying? https://issues.dlang.org/show_bug.cgi?id=16201 -- Andrei What I think about enchancement of static if is that it could be interesting to have `elif` keyword like in Python, so instead of static if (...) { } else static if(...) { } else static if(...) { } else { } I could write shorter: static if (...) { } elif (...) { } elif(...) { } else { } In other hand it maybe not got idea to have multiple syntax just for the same think. But we already have multiple syntax for template constraints template AA (T: int) {} or template AA(T) if ( is( T: int ) ) {} And also shorthand for template using *alias* was added recently: alias AA(T) = ... So my idea could survive too.. :) Bad thing here is adding the new keyword, but I don't think that people using word `elif` for names of their variables or functions, if they don't write Python parser of course :)
Re: Please rid me of this goto
On Friday, 24 June 2016 at 20:34:38 UTC, deadalnix wrote: On Friday, 24 June 2016 at 10:33:43 UTC, Patrick Schluter wrote: On Friday, 24 June 2016 at 10:11:11 UTC, deadalnix wrote: On Friday, 24 June 2016 at 08:40:26 UTC, Patrick Schluter wrote: On Thursday, 23 June 2016 at 20:01:26 UTC, deadalnix wrote: On Thursday, 23 June 2016 at 19:24:54 UTC, via Digitalmars-d wrote: On Thu, Jun 23, 2016 at 07:11:26PM +, deadalnix via Digitalmars-d wrote: | is bitwize or. || is binary or. & is bitwize and. && is binary and. ^ is bitwize xor. ^^ is... no, never mind. binary xor is != lol 3 != 5 is true. 3 binaryxor 5 is false. He meant logical xor, because binary xor exists (^) and there would be no point to mention an equivalence. Still doesn't work. It works if you cast each side of the comparison to boolean values (that's what logical and/or do implicitely, for != it has to be done explicitely as the operator has never been seen as logical xor). in C (sorry I'm not fluent in D yet). (bool)3 != (bool)5or old fashioned!!3 != !!5 or after De Morgan transformation !3 == !5. So, logical xor isn't != either is it ? It is, I shouldn't have posted the old fashioned (i.e. without C99 bool type) version, it has confused you. Let's see the truth table for logical xor and != a | b | a ^ b | a != b ---|-|| 0 | 0 | 0 | 0 0 | 1 | 1 | 1 1 | 0 | 1 | 1 1 | 1 | 0 | 0 omg, it's the same result, but you have first to reduce each side of the expression to its canonical boolean value 0 or 1 (false or true in Java or D). That's also what the logical && and || do, compared to & and |.
Re: [OT] ...
Btw, one might take the view that "pown(real x,int y)" is describing monomials: https://en.wikipedia.org/wiki/Monomial Whereas "powr(real x,real y)" is a shorthand for "exp(y * log(x))".