Re: [OT] Swift removing minor features to piss me off
I think Swift is not yet stable. So if you want to use it you have to deal with language changes (D2 is stable). In a modern language ++ and -- are OK only if they return void. Otherwise they are bug-prone and allow people to write less readable code. C for() loops are powerful, but a bit too much bug prone and they encourage too much compressed code. Better to push reasonable coding standards inside the language itself. Only const function arguments looks a bit excessive in defulting-to-const language, but I think it's acceptable if you have a way to make them mutable. It seems Swift is copying several things from Rust. Perhaps Swift is going to become more popular than Rust (because Rust is more bondage, less handy because of manual memory management, more fussy, and usually fitter for system coding, unlike Swift that is more general purpose, on the other hand Rust is a bit more free than Swift now). Bear hugs, bearophile
Re: final switch and straight integers
Dominikus Dittes Scherkl: final switch makes no sense on things that are not enumerated. Even on ubyte almost nobody will ever list all 256 cases, not to mention larger types. It's easy to cover all the values in a switch, using ranges. No need to forbid final switch for integral values. It just needs to be implemented correctly. Bye, bearophile
Re: D vs Rust
gour: For quite some time I was looking at Ada as potential language to write multi-platform desktop application, but, being the big language which requires lot of time and energy to invest into learning/mastering it, I, somehow, feel reluctant seeing that there is practically no open-source community around Ada, no truly open-source compile -- what would happen if AdaCore would simply pull the plug since I do not believe there are enough people capable to maintain/develop FSF GNAT, so I'd appreciate if you can write few words about Ada vs D hoping that the latter it one you are recommending for new (gui) projects? I simply hope that D can provide me with most/all the features I'd expect from the language like Ada, but but even more modern features, more choices when it comes to developing GUI desktop app, more compiler choices, better tooling and, of course, much bigger community of open-source enthusiasts. Ada language has several nice features worth stealing (I'd like both D and Rust to add constrained values, static preconditions, ranged subtypes, and annotations to control access to global variables), and if you're writing a train control system, a space probe/satellite, a military machine control, a hardware-constrained device that needs to be very reliable (like a medical machine working inside the body) then using Ada/SPARK could be reasonable. But for an average multi-platform desktop application Ada is not a good idea. The main problem is not the language itself (that is very verbose, but that's not a show-stopper), but the tooling (very scarce, and very pricey, very few compilers, very few IDEs, etc), the community (small), and the libraries (not many). A sufficiently rich and sufficiently determined group of programmers could probably write a regular desktop application in Ada, but you're walking uphill for not enough reason. Sometimes worse is better because it's actually overall better. There is a recent thread about Ada on Reddit, but unfortunately the best comment in that page has being deleted... :-) https://www.reddit.com/r/programming/comments/49y7sc/11_myths_about_ada/ Bye, bearophile
Re: D vs Rust
xenon325: Doesn't http://wiki.dlang.org/DIP25 fix this ? I think DIP25 is designed to be only a partial solution, it's not a complete memory safety story. Bye, bearophile
Re: D vs Rust
On Sunday, 31 January 2016 at 15:44:37 UTC, Laeeth Isharc wrote: Guillaume Piolat "- D is a large language, not sure how much relatively to Rust. I've heard Rust is complicated too." and yet, it's easy to get started if you know C. one can be quite quickly productive without having any experience of template metaprogramming, CTFE, and the like, and gradually absorb language features as you go. Phobos is pretty readable, on the whole. I agree with bearophile about GC making it easier in the beginning. bearophile: "I am sometimes able to write working D code almost as quickly as Python code" Yes, indeed - that's my experience too. I wonder what we could do to make this most of the time, if not almost always, and for less experienced programmers than you. It wouldn't be surprising to find that the things that tend to get in the way fall in certain common categories. Some people have applied machine learning to compilers to study this - that's probably beyond our resources for now, but the idea makes sense. Adam's and others' work on error messages might be part of the answer. Thank you for the colour on OcaML. What could be done to improve Algebraic and pattern matching? The talk at the London dmeetup was quite interesting, but I had the sense that was fairly experimental at this stage. "There are several kinds of code that D allows you to write quite better than Rust (generic application code, script-like code, explorative scientific numerical code (like ndslice), medium-integrity code, metaprogramming, compile-time computations, template-level computations and specializations, higher order template magic, and so on. " Should we make more of a feature of this in the intro page. Tutorials per category showing the value? And should the Rosetta stone examples (many of which you wrote, as I understand it) be more prominently featured? Maybe even in the code samples on the front page too. "In Ada you can be productive if you use it for the purposes it was invented for, but most times you don't write that kind of code." Thank you - yes that's what I figured, and it probably isn't for me. But I wanted to see if I was missing something. " I like languages that avoid me most common bugs," I wonder what the most common bugs and traps are in D. P0nce's D idioms allude to some of them, but that isn't the focus of what he writes. "I think D should relax and keep improving its strengths (like C++ interoperability), fix some of its holes (safety, GC-less programming, fixing its contract-driven programming experience, etc), improve its medium-integrity coding, and keep going on as usual, slowly getting better. The Rust and D niches are sufficiently different, there's minimal overlapping in their purposes and niches." Yes - I completely agree. As Peter Thiel says, competition is for losers. Much better to have a monopoly that you have earned (and have to keep earning). I agree with Knuth that language reflects thought and people intrinsically think differently (this also being shaped by the domain) - he welcomed the prospect of an expansion in the number and kinds of language available. It's funny how the most negative critics in this forum and who make diffuse statements about how D has lost the race often don't seem to contribute much code to making things better. Contrast with Manu, for example, who whilst spirited is actually through actually using the language and reporting concrete difficulties is directly driving the completion of some features. Walter - sorry about that. I need to get someone to help on that front as I have so little time. Should work now. Laeeth Guillaume Piolat: What could be done to improve Algebraic and pattern matching?< The number of developers working on D compiler, D design and Phobos is limited, and D is a large language. So it's better to focus the developing work on fixing and finishing the unfinished parts of D, instead of adding new ways to do the same things. And even if you want new D features, there are more important things to think about, like GC-less coding, C++ interoperability, async/await, and so on. I wonder what the most common bugs and traps are in D.< You have to take care of the less common bugs too if you want a reliable language. And currently it's dead-easy to write unsafe code even in @safe D functions: int[] foo() pure @safe { int[2] a = [10, 20]; auto b = a[]; return b; } void main() {} Now that Rust is showing some "intellectual" competition with C++, Stroustrup is even starting to think about adding some memory safety to C++ (but it's hard for this to become a complete memory safety for C++): https://isocpp.org/blog/2015/09/bjarne-stroustrup-announces-cpp-core-guidelines Regarding the code reliability, D is better than C++11, but it can be further improved, as Ada2012/SPARK show. On the other hand, a higher reliability has a
Re: D vs Rust
Laeeth Isharc: On Saturday, 30 January 2016 at 16:51:09 UTC, Laeeth Isharc wrote: I haven't used Ocaml, but was intrigued by it after seeing Yaron Minsky's talks. To what extent can pattern matching, strong types with invariants and other things Ocaml features be implemented idiomatically in D? Eg I know D has invariants, but that seems to be more a debug mode thing, and I am not sure if they are doing the same as what Minsky described in his talk. Rust allows you to write very OCaML-like code, the main difference is that you need to memory manage manually (and Rust doesn't have a GIL). D Algebraic isn't very good, and the D/Phobos pattern matching is minimal, so to write compiler-like code in D you need a style quite different from the OcaML/F#/SML/Haskell code. On the other hand Rust is less flexible, sometimes even C-like for loops are not handy to do in Rust. The Servo browser and the Rustc compiler are two of the main projects written in Rust, so sometimes Rust looks like a browswer-driven language, and this means Rust developers sometimes seem to not understand or not care that lot of people have other different needs. There are several kinds of code that D allows you to write quite better than Rust (generic application code, script-like code, explorative scientific numerical code (like ndslice), medium-integrity code, metaprogramming, compile-time computations, template-level computations and specializations, higher order template magic, and so on. In general Rust seems a more specialized language). How productive do you find coding in Ada ? In Ada you can be productive if you use it for the purposes it was invented for, but most times you don't write that kind of code. I miss some Ada features, and I've missed the strictness of the Ada compiler that catches lot of bugs, but for most things today I prefer a more modern languages. In Ada you need more time to write the code and make it run, but later you save some debugging time, even compared to D. I like languages that avoid me most common bugs, even if I need more time to write it. To write Ada code you need to remember lot of times, because Ada is a quite large language, but most things are quite logical and straightforward, so learning Ada is just a matter of having elephant's memory, you don't need to be smart. Rust is a much smaller language, but you need to think more about your code, otherwise it will never compile :-) D is more like Python, you don't need lot of memory to use it, and the garbage collector saves you lot of thinking (if you are writing small programs). I think D should relax and keep improving its strengths (like C++ interoperability), fix some of its holes (safety, GC-less programming, fixing its contract-driven programming experience, etc), improve its medium-integrity coding, and keep going on as usual, slowly getting better. The Rust and D niches are sufficiently different, there's minimal overlapping in their purposes and niches. Bye, bearophile
Re: D vs Rust
qznc: On Friday, 29 January 2016 at 09:00:52 UTC, qznc wrote: D is a broader language and is applicable in more situations. In many cases you don't care and don't want to care about memory management. Learning to manage memory in Rust takes lot of time and practice, it's a bit painful. I am sometimes able to write working D code almost as quickly as Python code, but writing similar code in Rust takes me much more time. So I think for both small script-like programs, and general application code (where code safety is not the most important thing), D wins over Rust. D is also more flexible (higher order templates, better CTFE, unrestricted UFCS, etc), and you can port Python or C code to D faster than to Rust. So I think Rust targets a smaller number of coding purposes compared to D. Rust could also replace the code you want to write in OcaML, like compiler-like programs (thanks to Rust enums and pattern matching). Safety and correctness of the code are very important for me. Regarding safety & correctness I think there's this ordering: Rust > D > C++14 > C If you talk about correctness you think about Ada too. Rust code seems usually more succinct compared to Ada code. Ada is more mature and it has lot of small features missing from Rust/D, that help make the code more correct (like integer subsets, static invariants, stronger typing for array indexing, SPARK annotations to manage global mutables safely, and so on). I don't know if such safety features will be added to Rust, I am dubious. In the C/Ada world you have language subsets like MISRA/SPARK that people use in high integrity system. I think Rust still lacks something like that. Bye, bearophile
Re: Can D interface with Free Pascal?
FreeSlave: On Thursday, 28 January 2016 at 08:15:38 UTC, FreeSlave wrote: Not directly. You can declare cdecl function on Free Pascal side and call it as extern(C). What about extern(Pascal)? https://dlang.org/spec/attribute.html#linkage Bye, bearophile
Re: How to represent struct with trailing array member
Dibyendu Majumdar: On Thursday, 21 January 2016 at 21:52:06 UTC, Dibyendu Majumdar wrote: How should this be translated to D? Will D's array access allow data elements to be accessed beyond the size declared? Take a look at the code I've written here: http://rosettacode.org/wiki/Sokoban#Faster_Version You can also add a constructor to such struct, for safety and disallow default construction. Bye, bearophile
Re: Convert some ints into a byte array without allocations?
Yazan D: On Saturday, 16 January 2016 at 14:42:27 UTC, Yazan D wrote: ubyte[] b = (cast(ubyte*) )[0 .. int.sizeof]; Better to use the actual size: ubyte[] b = (cast(ubyte*) )[0 .. a.sizeof]; Bye, bearophile
Re: Under 1000 opened bugs for Phobos
BBaz: So I don't know...and I ask, should the garbages from bearophile be closed ? Hello, I use D every day, and there are several functions that I'd like in Phobos. I think all/most of them can be of general usefulness. While I am often wrong, those ERs come from plenty of experience coding in D and other languages, so throwing them away *en masse* is unwise. They should be judged singularly. Bye, bearophile
Re: conver BigInt to string
Namal: Hello I am trying to convert BigInt to string like that while trying to sort it: void main() { import std.stdio, std.algorithm, std.conv, std.bigint, std.string; auto n = 17.BigInt ^^ 179; n.text.dup.representation.sort().release.assumeUTF.writeln; } Bye, bearophile
Re: conver BigInt to string
void main() { import std.stdio, std.algorithm, std.conv, std.bigint, std.string; auto n = 17.BigInt ^^ 179; n.text.dup.representation.sort().release.assumeUTF.writeln; } Better: n.to!(char[]).representation.sort().release.assumeUTF.writeln; Bye, bearophile
Re: array function
Namal: std::vector foo(int N){ std::vector V(N); int some_array[N]; VLAs are not present in D. Bye, bearophile
[Rosettacode] sum of powers conjecture
I've translated the C++ entry to D as third D entry, but it's not a good translation, I've just converted iterators to pointers instead of using ranges (the resulting speed is acceptable). You're welcome to improve it: http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture#Third_version Bye, bearophile
Re: a success story for D ! !!
ponce: Paper: http://vlang.org/dvcon2014.pdf I'd say that's pretty huge! Very nice. Bye, bearophile
Re: Ada to D - an array for storing values of each of the six bits which are sufficient
Dennis Ritchie: Anybody can write a packed array on the D? I once badly represent the means by which we can write a packed array. Maybe for this you should use core.simd or unions? SIMD could be useful for some fancy bulk operations. But you should be able to write a good basic packed array without SIMD, perhaps about as nice as the Ada ones (D sometimes offers good enough tools to build what you need). Posible use: PackedDynamicArray!6 pa; // On heap. PackedFixedArray!(6, 300) pfa; // On stack. Bye, bearophile
Re: Ada to D - an array for storing values of each of the six bits which are sufficient
Dennis Ritchie: There is an array of values to store each of which sufficiently 6 bits. As it is written down on the D? You can't do it directly in D. Someone has to write a packed array data structure to do it. Bye, bearophile
Re: if(arr) now a warning
Andrei Alexandrescu: I have no doubt the change can find certain errors. Problem is false positives. FWIW these are the changes I had to operate on std.allocator to make it work with the new compiler. One per 194 lines on average, all false positives: Just fix your code Andrei Alexandrescu :-) Bye, bearophile
Re: Implicit conversion error
Paul: When compiled on a 64 bit machine, this line int r = uniform(0, mobs.length); .length returns a size_t, and 0 is an int. uniform() probably decides to unify those types to a size_t. A size_t is 32 bit on 32 bit machines and 64 bits on 64 bit machines. But D int is always a 32 bit signed integer. D allows implicit assignment of a 32 bit size_t to int but not a 64 bit size_t to an int. I agree that it's a bit of a mess. Bye, bearophile
Re: if(arr) now a warning
Steven Schveighoffer: FYI, Andrei and Walter are reversing this change barring any new evidence it's helpful to people. Please speak up if you disagree. There's no more evidence. It's an improvement, for people coming from Python. The current semantics is not meaningful. One of the points of D over C++ was to fix irrationally designed parts, like this small problem. Many small design mistakes like this one create C++ we know and hate. We should fix such small problems quickly and look forward, instead of debating forever and reverting every small step forward like this. My presence around here is becoming useless. Bye, bearophile
Re: [hackathon] An article about metaprogramming
Mafi: https://marfisc.wordpress.com/2015/04/29/using-d-templates-for-gamedev/ What do you think? Any remarks? The SDL_Event is a union. Accessing it is inherently unsafe for type consistency and memory safety. The SDL library mitigates this problem by adding a tag (the member type) which encodes which union-member is to be used. In Rust you use the built-in tagged unions and call it a day... switch(polledEvent.type) { mixin(caseOnEvent!(SDL_QUIT, quit)); mixin(caseOnEvent!(SDL_ACTIVEEVEENT, active)); mixin(caseOnEvent!(SDL_KEYDOWN, eventKeyDown)); // (*) mixin(caseOnEvent!(SDL_KEYUP, eventKeyUp)); // (*) mixin(caseOnEvent!(SDL_MOUSEMOTION, motion)); mixin(caseOnEvent!(SDL_MOUSEBUTTONUP, eventMouseButtonUp)); // (*) mixin(caseOnEvent!(SDL_MOUSEBUTTONDOWN, eventMouseButtonDown)); // (*) mixin(caseOnEvent!(SDL_JOYAXISMOTION, jaxis)); mixin(caseOnEvent!(SDL_JOYBALLMOTION, jball)); mixin(caseOnEvent!(SDL_JOYHATMOTION, jhat)); mixin(caseOnEvent!(SDL_JOYBUTTONDOWN, eventJoyButtonDown)); // (*) mixin(caseOnEvent!(SDL_JOYBUTTONUP, eventJoyButtonUp)); // (*) mixin(caseOnEvent!(SDL_USEREVENT, user)); mixin(caseOnEvent!(SDL_SYSWMEVENT, syswm)); default: //has to be there even if empty static if(is(typeof(that.onOther(Event.init { that.onOther(polledEvent); break; } } The default should be aligned just like the other cases. Often is a good idea to use final switch with enumerations. Probably there are ways to make that code more dry, using a TypeTuple of pairs like (SDL_QUIT, quit). Bye, bearophile
Re: Possible to write a classic fizzbuzz example using a UFCS chain?
Gary Willoughby: I wondered if it was possible to write a classic fizzbuzz[1] example using a UFCS chain? I've tried and failed. Is this OK? void main() { import std.stdio, std.algorithm, std.range, std.conv, std.functional; 100 .iota .map!(i = ((i + 1) % 15).predSwitch( 0, FizzBuzz, 3, Fizz, 5, Buzz, 6, Fizz, 9, Fizz, 10, Buzz, 12, Fizz, /*else*/ i.text)) .reverseArgs!writefln(%-(%s\n%)); } Bye, bearophile
Re: C++ const expression are not that const after all
Luc Bourhis: The author of that blog seems to see his finding in a positive light actually. As it makes it possible to write more powerful template metaprograms! One of the essences of modern languages is to restrict the power of the programmer in specific parts, to reduce unwanted interactions and make complexity more manageable. His finding seems a design mistake. Bye, bearophile
Re: function ref param vs pointer param
On Friday, 24 April 2015 at 13:39:35 UTC, ref2401 wrote: processPointer(ms); I think doing this way is more descriptive. Now all readers know that ms might be changed inside the function. C# avoids that problem requiring (in most cases) the usage of ref at the calling point too. But this idea was refused for D (also because it goes against UFCS chains). Bye, bearophile
Re: function ref param vs pointer param
ref2401: void processRef(ref MyStruct ms) { writeln(processRef: , ms); } void processPointer(MyStruct* ms) { writeln(processPointer: , *ms); ref params don't need the * every time you use them inside the function, and don't need the when you call the function. Bye, bearophile
Re: switch case expressions
Martin Krejcirik: So, should the case b compile or not ? Is the spec too restrictive here, or is it a bug ? Apparently it's a WONTFIX mess. The spec should be updated. WalterAndrei refused to fix a design bug here. Bye, bearophile
Re: Cleaned up C++
Walter Bright: On 4/22/2015 2:58 PM, bearophile wrote: D is less stack-friendly than Ada (and probably Rust too), ?? In Ada standard library you have safe fixed-size stack-allocated associative arrays. In D you can't even allocate safely a dynamically-sized 1D array on the stack, and forget about doing it for 2D. Enough said. Bye, bearophile
Re: Cleaned up C++
weaselcat: On Wednesday, 22 April 2015 at 19:29:08 UTC, Walter Bright wrote: D is just another of those “Let's put everything on the heap”-languages that do then of course need GC. what's up with people constantly equating garbage collection to being the same as java? In D you don't put everything on the heap. D is less stack-friendly than Ada (and probably Rust too), but in D you allocate lot of small stuff on the stack. Bye, bearophile
Re: multiSort for sorting AA by value
Chris: I'm happy with it, but maybe there is a more concise implementation? This is a bit shorter and a bit better (writefln is not yet able to format tuples nicely): void main() { import std.stdio: writeln; import std.algorithm.sorting: multiSort; import std.array: array; const size_t[string] wCount = [ hamster: 5, zorro: 80, troll: 90, algorithm: 80, beer: 80 ]; auto pairs = wCount.byKeyValue.array; assert(wCount.length == pairs.length); pairs.multiSort!(q{a.value b.value}, q{a.key b.key}); assert(pairs[2].key == beer); foreach (const ref it; pairs) writeln(it.key, : , it.value); } Bye, bearophile
Re: Structural exhaustive matching
Jadbox: I'm curious on what the best way to do ADTs in D. Sometimes there's no best way, there are several alternative ways with different tradeoffs. D isn't a functional language and there's no really good way to do ADTs in D. You can use plus a final switch. Or you can use Algebraic from Phobos. Sometimes you can use another Phobos function that simulates an improved switch. Or often you can just give up at using ADTs in D and use what other solutions D offers you (like OOP). Bye, bearophile
Re: Vectorization examples
Walter Bright: Use arrays of double2, float4, int4, etc., declared in core.simd. Those will be aligned appropriately. Is the GC able to give memory aligned to 32 bytes for new architectures with 512 bits wide SIMD? and a way to tell the type system that some array slices are fully distinct (the __restrict seen here, I think this information doesn't need to be part of a type). A runtime test is sufficient. One of the points of having a type system is to rule out certain classes of bugs caused by programmers. The compiler could use the type system to add those runtime tests where needed. And even better sometimes is to avoid the time used by run time tests, as shown in that video, using the static information inserted in the code (he shows assembly code that contains run time tests). Another example of missing static information in D is shown near the end of the video, where he shows an annotation to compile functions for different CPUs, where the compiler updates function pointers inside the binary according to the CPU you are using, making the code safe and efficient. Bye, bearophile
Re: D vs nim
Russel Winder: it is all part of guerilla marketing undertaken by anyone with anything to market. It's still not a correct behavour, regardless how many do it. Bye, bearophile
Vectorization examples
Utilizing the other 80% of your system's performance: Starting with Vectorization by Ulrich Drepper: https://www.youtube.com/watch?v=DXPfE2jGqg0 It shows two still missing parts of the D type system: a way to define strongly typed byte alignments for arrays (something better than the aligned() shown here, because I prefer the alignment to be part of the type), and a way to tell the type system that some array slices are fully distinct (the __restrict seen here, I think this information doesn't need to be part of a type). Bye, bearophile
Re: Converting Java code to D
John Colvin: struct LineStyle { enum NONE = None; enum SOLID = Solid; enum DASH = Dash; enum DOT = Dot; enum DASHDOT = Dash Dot; enum DASHDOTDOT = Dash Dot Dot; string label; private this(string label) { this.label = label; } } The constructor doesn't look very useful. Perhaps a named enum is safer. Bye, bearophile
Re: How about appender.put() with var args?
Márcio Martins: app.put(foo); app.put(var); app.put(bar); I'd like put() to accept a lazy range... Bye, bearophile
Re: Programming languages and performance
weaselcat: It's reddit, that's not really surprising. Do you know a place better than Reddit for general programming discussions? The lambda the ultimate blog is not generic. Bye, bearophile
Re: Does 'D' language supports 'C' like VLA?
John Colvin: The problem is that the size isn't necessarily known. The size is generally known only at run-time, that's the point. I guess the compiler could put in a branch, but at that point you'd probably want to give the programmer control and have a way of making it explicit. You don't forget to put branches added by the compiler, so it's safer. Generally you prefer something that's guaranteed to be allocated on the stack when it's small and there's enough stack. An array allocation annotated with scope, perhaps. Bye, bearophile
Re: Programming languages and performance
Walter Bright: Algorithms don't actually do deforestation or fusion. The magic happens in how the algorithm is implemented, i.e. the elements are created lazily (on demand) rather than eagerly. Stream fusion is often about laziness. There is a ton of literature about this topic. Bye, bearophile
Re: Does 'D' language supports 'C' like VLA?
Steven Schveighoffer: It's very unlikely this will make it into the language. Alloca should be good enough for this, it's not a very common usage, and supporting it is not easy. alloca is bug-prone and unsafe, and if you want to create a 2D array on the stack it's not good enough. They are uncommonly used because they are not supported by the D compiler, and it doesn't track the memory ownership well enough. But a well designed system language needs to push programmers to use the stack as much as possible. Bye, bearophile
Re: DIP77 - Fix unsafe RC pass by 'ref'
Marc Schütz: You have to keep in mind that this is opt-in; it only applies to `scope` variables. I would agree that as a default, it wouldn't fit D at all. I think that, for all its usefulness, it'd be a tad too limiting for my taste if I were forced to use it everywhere. I think D Zen asks for safety on default and opt-out on request. See also @safe by default: https://issues.dlang.org/show_bug.cgi?id=13838 Bye, bearophile
Re: Function name from function pointer
Paul D Anderson: Is there a way to return the name of a function (a string) from a pointer to that function? Perhaps creating a string[void*] AA and initializing with all the function pointers you care about. Bye, bearophile
Re: if(arr) now a warning
Steven Schveighoffer: What do you think? I asked for this fix almost five years ago, so I think it's about time :-) Bye, bearophile
Re: Generating all combinations of length X in an array
wobbles: Have just tested, it is! But with the current D front-end it's not a good idea to generate too many combinations at compile-time. Efficient code doesn't save you from bad usages. Bye, bearophile
Re: return the other functions of the void main()
Jack Applegame: writeln(a.find(4).empty ? No : Yes); canFind? Bye, bearophile
Re: Generating all combinations of length X in an array
wobbles: While trying to generate all combinations of length X in an array, I came across the question on stackoverflow. [1] Theres a couple good answers there, but one that caught my eye shows a C# code snippet that is quite nice and short: Often short code is not the best code. Take a look at the versions here, the usable one is the third: http://rosettacode.org/wiki/Combinations#D Bye, bearophile
Re: Implementing Iterator to support foreach
tcak: I am planning to implement Iterator class. But looking at foreach statement, it takes a range only. Unless you are just experimenting, it's better to not go against a language and its std lib. Bye, bearophile
Re: Why I'm Excited about D
deadalnix: foreach (name; names.parallel) { name.writeln; } no.please I think foo.writeln; is acceptable. You just need to get a bit used to it. Bye, bearophile
Re: function shadowed
ddos: same behavior when overriding methods of base classes This is by design. Bye, bearophile
Re: DIP76: Autodecode Should Not Throw
Vladimir Panteleev: std.conv doesn't return NaN if you try to convert banana to a double. I have suggested to add a nothrow function like maybeTo that returns a Nullable result. Bye, bearophile
Re: Shall I use immutable or const while passing parameters to functions
tcak: void dataProcessor( string giveMeAllYourData ){} dataProcessor( cast( immutable )( importantData[5 .. 14] ) ); With Const, void dataProcessor( in char[] giveMeAllYourData ){} dataProcessor( cast( const )( importantData[5 .. 14] ) ); Don't cast to const/immutable unless you have a good reason to do it, and you know what you are doing (and most times you don't know it). More generally, minimize the number of cast() in your D programs. You can use a search to count how many cast( there are in your whole D codebase, and you can try to reduce that number. Bye, bearophile
Re: Fun project - faster associative array algorithm
w0rp: It doesn't amaze me at the moment, as it's slightly faster for integers, and slightly slower for strings at the moment. One problem with D strings is that they don't cache their hash value. Bye, bearophile
Re: Fun project - faster associative array algorithm
Andrei Alexandrescu: A possible cache-friendly replacement would be an array of buckets with local probing to resolve collisions. Arrays would need to move data. Current hashtables rely on values staying put. -- Andrei The efficiency behavour of modern CPUs+memory pyramid are rather not linear and not intuitive. As Walter has said at the the start of this thread, arrays come out as more efficient in a large number of cases... Bye, bearophile
Re: Questions about phobos additions mentioned in 2015H1 vision document
Andrei Alexandrescu: 1. Are you wanting a large batteries included standard library a'la Python[2] or only focused around the aspects mentioned? Batteries included. This is a quite significant decision. It has both advantages and disadvantages. (I think Rust has chosen to have a lighter std lib). Bye, bearophile
Re: Issue with free() for linked list implementation
Namespace: I've written a straight forward linked list implementation here: https://github.com/nomad-software/etcetera/blob/master/source/etcetera/collection/linkedlist.d Even though I'm using the GC to manage memory, maybe it will help you. Good idea to link to some existing code. Here is mine: https://github.com/Dgame/m3/blob/master/source/m3/List.d In 99%+ of cases it's a bad idea to use a linked list. Bye, bearophile
Re: The next iteration of scope
Walter Bright: I'm not convinced of the need for overloading on 'scope'. Do you want to explain some of the advantages and disadvantages of that? It will help understand your reasons. Bye, bearophile
Re: Benchmark of D against other languages
Martin Nowak: Your persistent interest in integer overflow checks make we wonder if you were responsible for this? http://www.around.com/ariane.html I am not responsible for that, but I try to not be responsible for future molecular biology mistakes equivalent to that Ariane fiasco. Bye, bearophile
Re: Benchmark of D against other languages
weaselcat: was it a conscious decision to make the AA [] operator not work like map/etc in C++? What do you mean? accessing a non-existing element in C++'s map/unordered_map inserts the default instead of raising an exception int main(int argc, char *argv[]) { std::unordered_mapstd::string, int test; std::cout test[hello] std::endl; return 0; } prints 0 void main() { int[string] test; writeln(test[hello]); } core.exception.RangeError@source/main.d(9): Range violation Yes, it was a conscious decision, because here C++ behaves in a very bug-prone way. Sometimes C++ is a bad example to follow (like with permutations generations, that currently is not a Range in Phobos for the wrong reasons). Bye, bearophile
Re: Benchmark of D against other languages
Andrei Alexandrescu: Oh boy all classes with one-liner non-final methods. Manu must be dancing a gig right now :o). -- Andrei Yes, the right default for D language should be final, because lot of programmers are lazy and they don't add attributes. Bye, bearophile
Re: Speed of horizontal flip
tchaloupka: Am I doing something utterly wrong? If you have to perform performance benchmarks then use ldc or gdc. Also disable bound tests with your compilation switches. Sometimes reverse() is not efficient, I think, it should be improved. Try to replace it with a little function written by you. Add the usual pure/nothrow/@nogc/@safe annotations where you can (they don't increase speed much, usually). And you refer to flip as method, so if you are using classes don't forget to make the method final. Profile the code and look for the performance bottlenecks. You can even replace the *w multiplications with an increment of an index each loop, but this time saving is dwarfed by the reverse(). Bye, bearophile
Re: Benchmark of D against other languages
Martin Nowak: GCC5 comes with a big announcement about devirtualization. https://www.gnu.org/software/gcc/gcc-5/changes.html#general I have a small question. That page says: A new set of built-in functions for arithmetics with overflow checking has been added: __builtin_add_overflow, __builtin_sub_overflow and __builtin_mul_overflow and for compatibility with clang also other variants. These builtins have two integral arguments (which don't need to have the same type), the arguments are extended to infinite precision signed type, +, - or * is performed on those, and the result is stored in an integer variable pointed to by the last argument. If the stored value is equal to the infinite precision result, the built-in functions return false, otherwise true. The type of the integer variable that will hold the result can be different from the types of the first two arguments. The following snippet demonstrates how this can be used in computing the size for the calloc function: void * calloc (size_t x, size_t y) { size_t sz; if (__builtin_mul_overflow (x, y, sz)) return NULL; void *ret = malloc (sz); if (ret) memset (res, 0, sz); return ret; } On e.g. i?86 or x86-64 the above will result in a mul instruction followed by a jump on overflow. Now both GCC and Clang have intrinsics to perform safe integral operations. In recent versions of druntime/dmd there are functions to perform some safe integer operations. So is the API very well compatible with those intrinsics? Bye, bearophile
Re: The next iteration of scope
Walter Bright: I'm thinking of a modest step which would be a subset of your proposal: 1. implement 'scope' and 'return' for arrays, classes, and pointers 2. implement inference for templates and lambdas 3. enable it with the -dip25 switch and see how far that takes us. This is interesting. For the final D programmer what's the practical difference between your proposed subset compared to the full proposal? Bye, bearophile
Re: Gary Willoughby: Why Go's design is a disservice to intelligent programmers
Ola Fosheim Grøstad: So, it will just fade way in the sea of JavaScript wannabe replacements. Maybe, but Google is using it for Google Ads. Which is their primary business? Still, a bit early to say what happens next. Perhaps next some kind of blend of Typescript and Dart will become part of a next JavaScript update :-) Bye, bearophile
Re: What ?
Brian Schott: Do this instead: ulong u = 1L 63; I suggest a more explicit: ulong u = 1UL 63; Alternative: ulong u = 2UL ^^ 63; Bye, bearophile
Re: Adding sets to the language.
w0rp: Every now and then I want a set type, I think you can implement good enough sets in Phobos, do you agree? But you can't do the same with tuples. So I prefer sets in Phobos and tuples in the language. Bye, bearophile
Re: Associative Array of Const Objects?
bitwise: I'm a little confused at this point why this doesn't work either: const and immutable are rather different between C++ and D, I suggest you to take a look at the documentation: http://dlang.org/const-faq.html Bye, bearophile
Re: Associative Array of Const Objects?
bitwise: class Test{} void main() { const(Test)[string] tests; tests[test] = new Test(); } This code used to work, but after upgrading to dmd 2.067, it no longer does. --Error: cannot modify const expression tests[test] How do I insert an item into an associative array of const objects? You meant to say associative array with const objects as values. I think the short answer is that you can't. This is a breaking change, I think, it broke some of my code too. But perhaps something like Rebindable could be used. Bye, bearophile
Re: Why dont dlang check NullPointer?
zhmt: In short words, I want to catch something like NullPointerException. Is this possible? One solution is to add null tests to D in nonrelease mode. A better solution is to modify D to remove all or most chances of dereferencing null pointers and class references. Bye, bearophile
Re: [Phobos] You're crippled by your orthodoxism
Jean pierre: This is a problem, you, the D core has: you're crippled by your orthodoxism. Nothing will be added because of this: **rules**. The current level of acceptance of Phobos patches seems roughly correct to me. Bye, bearophile
Re: D's type classes pattern ?
matovitch: I am curious to know how isInputRange is implemented since I wanted to do kind of the same but I am afraid it's full of (ugly) traits and template trickeries where haskell type classes are quite neat and essentially a declaration of an interface. Take a look at the sources and learn. They are sometimes tricky to get right, but it's not a problem of ugly syntax. I wondered if you could check statically that the type could implement an interface *if it wanted to* that is, without inheriting it... Template constraints don't require inheritance. Bye, bearophile
Re: Keep Track of the Best N Nodes in a Graph Traversal Algorithm
Nordlöw: I have graph traversal algorithm that needs to keep track of the N best node visit. std.algorithm.topNCopy? Bye, bearophile
Re: C# to D
Dennis Ritchie: int[] arr = { 7, 5, 7, 3, 3, 5, 3, 3, 0, 3, 1, 1, 5, 1, 1, 1, 2, 2, 8, 5, 8, 8 }; Console.WriteLine(string.Join( , arr.OrderByDescending(x = arr.Count(y = y == x)).ThenBy(x = x))); // prints 1 1 1 1 1 3 3 3 3 3 5 5 5 5 8 8 8 2 2 7 7 0 One solution: void main() { import std.stdio, std.algorithm, std.typecons; auto arr = [7, 5, 7, 3, 3, 5, 3, 3, 0, 3, 1, 1, 5, 1, 1, 1, 2, 2, 8, 5, 8, 8]; arr .schwartzSort!(x = tuple(-arr.count!(y = y == x), x)) .writeln; } Bye, bearophile
Re: C# to D
.schwartzSort!(x = tuple(-arr.count!(y = y == x), x)) But calling count for each item is not efficient (in both C# and D). If your array is largish, then you need a more efficient solution. Bye, bearophile
Re: C# to D
Ali Çehreli: Do you know the story about groupBy? It's a long messy story. Look for it with another name, like chunkBy or something like that. Bye, bearophile
Re: C# to D
Ivan Kazmenko: (1) For me, the name of the function is obscure. Something like sortBy would be a lot easier to find than schwartzSort. I've asked to change the name of that function for years. But Andrei Alexandrescu is a adamantly against changing that pet name he has chosen. This is irrational behavour: https://issues.dlang.org/show_bug.cgi?id=4909 There's lot of way to go for Phobos. And the only want to find holes, missed opportunities, sub-optimal performance spots, missing functions and features, and bad APIs and bad names is to actually try to use Phobos, like we are doing in this thread. Bye, bearophile
Re: C# to D
Dennis Ritchie: A more effective solution for C ++: #include iostream #include vector #include range/v3/all.hpp int main() { using namespace ranges; auto rng = istreamint( std::cin ) | to_vector | action::sort | view::group_by( std::equal_toint() ) | copy | action::stable_sort( []( const auto e1, const auto e2 ) { return distance( e1 ) distance( e2 ); } ); std::cout ( rng ); } This is still not very efficient (perhaps the last sorting has to be stable): void main() { import std.stdio, std.algorithm, std.typecons, std.array; [7, 5, 7, 3, 3, 5, 3, 3, 0, 3, 1, 1, 5, 1, 1, 1, 2, 2, 8, 5, 8, 8] .sort() .groupBy!((a, b) = a == b) .map!array .array .sort!q{a.length b.length} .joiner .writeln; } Bye, bearophile
Re: Gary Willoughby: Why Go's design is a disservice to intelligent programmers
Ola Fosheim Grøstad: Downplaying other languages makes the D crowd look desperate... That kind of articles are bad for the image of the D community (and the D code shown in that article is not the best). Bye, bearophile
Re: C# to D
Ivan Kazmenko: arr.map !(to !(string)) .join ( ) .writeln; I suggest to not put a space before the bang (!), because it's confusing for me. Also, arr.map !(to !(string)) is better written arr.map!text. But even better is to use the range formatting of writefln, avoiding the map, to, and join, something like: writefln(%(%d %), arr); Bye, bearophile
Re: uniform tuple syntax
Vlad Levenfeld: Anything going on with this? Been looking forward to seeing it for awhile. It will happen. Bye, bearophile
Re: Keep Track of the Best N Nodes in a Graph Traversal Algorithm
Nordlöw: Ahh, a Binary Heap perfectly matches my needs. https://en.wikipedia.org/wiki/Binary_heap http://dlang.org/phobos/std_container_binaryheap.html But isn't topNCopy using a heap? Bye, bearophile
Re: dfmt options
Jacob Carlborg: Although I would like that the D syntax allowed to drop the curly braces, like with if-satements. That would result in much nicer one-liner functions. See: https://issues.dlang.org/show_bug.cgi?id=7176 Bye, bearophile
Re: A few notes on choosing between Go and D for a quick project
Andrei Alexandrescu: You may want to answer there, not here. I've also posted a response. There is this, with an attach: https://issues.dlang.org/show_bug.cgi?id=11810 Bye, bearophile
Re: Do strings with enum allocate at usage point?
岩倉 澪: However, if enum implies allocation at the usage point for strings, There are two ways to see if something allocates: there is a compiler switch, and an annotation: void foo() @nogc { // Your code here } If the compiler doesn't have a bug it will complain if you put something that allocates inside that function. Bye, bearophile
Re: A few notes on choosing between Go and D for a quick project
Elazar Leibovich: I personally, would have no idea what this piece of code is doing upon first sight. I'll have to look at the documentation of at least two functions to understand that, and I'll have to think carefully about what and who would throw in case of an error. Something like while (n != EOF) { n = read(fd, buf, sizeof(buf)); if (n==-1) throw(...); if (strcmp(buf, PREFIX) == 0) { return buf; } } return NULL; Requires no prior knowledge, and have similar effect. I'd rather have a loop written by hand in my production code any day, so that when debugging it, and reading it I'll have easier time to understand it, even though it would cost me a few more lines when writing the code. Unfortunately your thinking is mostly obsolete, the programming world (well, most of it, Go is one exception) is going in the opposite direction, and for good reasons. An explanation: https://channel9.msdn.com/Events/GoingNative/2013/Cpp-Seasoning Bye, bearophile
Re: A few notes on choosing between Go and D for a quick project
CraigDillabaugh: You said that Unfortunately this thinking is going out of style for good reasons. I am confused (sorry, I am at work, and didn't have time to watch the 1+ hour video you linked to - I said unfortunately because it's another reason for us to refactor and change our coding habits :-) maybe some clues were there)! Of course. I often find myself feeling a bit like Elazar. Not long ago I wrote some Python code using a bunch of the functional style programming tools and I was very please with the very concise code I had generated. Then, I had to make some modifications to the code. It took me an inordinate amount of time just to figure out what the code was doing, and I had written it myself just a few days earlier! There's not a single correct answer to this. Replacing long bug-prone explicit-loops code with pre-made safer algorithms is often a good idea. The effort of learning some very generic and reusable functions is usually worth it. But I've also seen plenty of Haskell code that requires you to know tens of tiny functions, often named with symbols like !!. This is worse than writing for loops. High level constructs in D are often slower than low-level code, so in some cases you don't want to use them. So as usually you have to choose wisely, because most solutions aren't perfect if you use them everywhere, there are many ways to write bad code if you don't keep your eyes and brain switched on. Bye, bearophile
Re: Replace core language HexStrings with library entity
Baz: https://github.com/D-Programming-Language/phobos/pull/3058 I suggest to replace litteral with literal, as in computer science: http://en.wikipedia.org/wiki/Literal_%28computer_programming%29 Bye, bearophile
Re: The next iteration of scope
Marc Schütz: Here's the new version of my scope proposal: http://wiki.dlang.org/User:Schuetzm/scope2 Let's see what Andrei and Walter think about this all :-) Bye, bearophile
Re: How to generate a random string ...
Robert burner Schadek: ... from all Unicode characters in an idiomatic D way? Perhaps by rejection? I mean, generating a uint, test if it's a character and repeat until the result is true. Bye, bearophile
Re: Replace core language HexStrings with library entity
Andrei Alexandrescu: That opens the question whether we want only ubyte[] for hex bytes or all integral types. I suggest to implement only ubyte[] first. And wait for enhancement requests. Bye, bearophile
Re: A few notes on choosing between Go and D for a quick project
ninja: 2. Please stop changing the (core) language all the time. There are like 3 new proposals every week in the forums and at least 2 of those are seriously considered. Please, just stop. D is not yet finished. Ownership of memory in D is a work-in-progress. Tuples are a hole in a language that wants to be a little functional. Alternative ways to allocate memory are needed by some people. The GC needs improvements. Purity is not yet finished. And there are minor things that can be improved. D3 is not planned, so the only way is to improve D2. Bye, bearophile
Template constraints
Observe: https://github.com/D-Programming-Language/phobos/pull/3054 Is this change the partial proof of another failure of a part of D language design? What's the point of template constraints? Aren't C++ Concepts better? Or to rephrase that in a less trollish way, can D be enhanced to add user-defined error messages to template constraints, and is such enhancement a good idea? Bye, bearophile
Re: A few notes on choosing between Go and D for a quick project
Walter Bright: I'd also prefer to get rid of /+ +/ comments, I thought they'd be more useful than they are. I prefer to get rid of /* */ instead :-) Because /++/ can do things /**/ can't. Bye, bearophile
Re: Replace core language HexStrings with library entity
Marc Schütz: Can we make it so it returns a ubyte[]? There is an enhancement request on this (for the built in hex strings). Bye, bearophile
Re: get from tuple by type
Charles Cooper: Yes, I could say external_api1_react_to_event(event_t[1], event_t[0]) .. but that is barbaric. It's a productivity sink because I have to go back to the original definition, align the arguments, and then context switch back to whatever I was working on before. If you are experiencing those problems it's probably the way D/Phobos to tell you to not use basic tuples for your purpose. Use tuples with named fields (or even structs). Take also a look at Algebraic in std.variant. Bye, bearophile
Re: Replace core language HexStrings with library entity
Andrei Alexandrescu: hexString and hexBytes. -- Andrei Can you show me one or two different use cases of hexString? Bye, bearophile
Re: Replace core language HexStrings with library entity
Walter Bright: Unfortunately, it needs to be a dropin replacement for x..., which returns a string/wstring/dstring. This is bad. 99% of the times you don't want a string/wstring/dstring out of a hex string: https://issues.dlang.org/show_bug.cgi?id=10454 https://issues.dlang.org/show_bug.cgi?id=5909 Bye, bearophile
Re: Dlang seems like java now,but why not let d more like C# Style?
dnewer: but,C# cant compiled to native code. Soon you will be able to compile C# natively. Bye, bearophile
Re: A few notes on choosing between Go and D for a quick project
Russel Winder: (*) IPython grew out of Python and become the de facto system, but was a mess structurally. IPython is splitting into IPython the original thing and Jupyter all the UI related stuff Jupyter looks like a nice idea and a nice project. I'd like to understand how Jupyter compared to Sage. Bye, bearophile
Re: A few notes on choosing between Go and D for a quick project
Paolo Invernizzi: I'm the only one so old, that for me, studying a language from a book is the normal pattern to follow for learning it? I think it's also a matter of how you usually learn. If you are a person that loves nonfinction books a lot, that reads nonfinction books a lot, then probably you also like to read a language with the help of a book. Bye, bearophile
Re: Compilation changes
Ali Çehreli: That may be related to the recent changes in the build system. Right. Have you been following the following threads? (I haven't been; so, I am sure whether they apply.) I have not. [dmd-internals] DMD now requires a working D compiler to be build Proposal : aggregated dlang git repository dmd 2.066.1 cannot build phobos 2.066.1 I will try to get something out of those threads, thank you :-) Bye, bearophile