Re: transversal sum

2014-11-07 Thread bearophile via Digitalmars-d-learn
Marc Schütz: auto sums = input .transposed .map!(a => a.sum); And that part is better written: .map!sum; I also suggest to align the leading dot to the precedent line: auto sums = input .transposed .map!

Re: transversal sum

2014-11-07 Thread bearophile via Digitalmars-d-learn
Marc Schütz: int[][] input = new int[][2]; input[0] = [1, 2, 3, 4]; input[1] = [5, 6, 7, 8]; writeln(input); auto sums = input .transposed .map!(a => a.sum); writeln(sums); } Output: [[1, 2, 3, 4], [5, 6,

Re: transversal sum

2014-11-06 Thread bearophile via Digitalmars-d-learn
Marc Schütz: We'd need something taking and returning a RoR that "mirrors" them diagonally. Then we could simply apply `map!(r => r.sum)` on the result. A simple solution is to create a row of values, and then sum them correctly while you scan the rows. Bye, bearophile

Re: Share array element between threads

2014-11-06 Thread bearophile via Digitalmars-d-learn
Misu: void main(string[] args) { class Account { public this(int id) { this.id = id; } int id; } ... This is not an answer to your question, but note: void main() { class Foo {} static class Bar {} pragma(msg, __traits(classI

Re: Curiously Cyclic Template Pattern causes segfault?

2014-11-05 Thread bearophile via Digitalmars-d-learn
Justin Whear: --any compiler crash is a bug regardless of whether the source is valid D code or not. I suspect that in some cases those compiler crashes are a way for the compiler to tell the programmer that the code was too much hairy and too much hard to understand ;-) Bye, bearophile

Re: Access Violation Tracking

2014-11-05 Thread bearophile via Digitalmars-d-learn
Bauss: Is there any way to track down access violations, instead of me having to look through my source code manually. I have a pretty big source code and an access violation happens at runtime, but it's going to be a nightmare looking through it all to find the access violation. Not to ment

Re: The interface's 'in' contract passes if it makes a virtual function call

2014-11-04 Thread bearophile via Digitalmars-d-learn
Ali Çehreli: Perhaps I am expecting too much from the current 'in' contract design and implementation. ;) The "in contract" is named pre-condition, or precondition. Bye, bearophile

Re: isRangeOf ?

2014-11-04 Thread bearophile via Digitalmars-d-learn
Jonathan M Davis: That loses the ability to test which type of range you're talking about. Yes, one can think about templates like "isForwardRangeOf", etc. But for such specialized cases I think using isForwardRange+is(ElementType) is acceptable and avoids adding too many templates to Phobo

isRangeOf ?

2014-11-04 Thread bearophile via Digitalmars-d-learn
Sometimes I have a function that needs an iterable: void foo(Range)(Range data) if (isForwardRange!Range && is(Unqual!(ForeachType!Range) == int)) {} So is it a good idea to add a "isRangeOf" template to Phobos? void foo(Range)(Range data) if (isRangeOf!(Range, int)) {} Bye, bearophile

Re: More flexible sorted ranges?

2014-11-02 Thread bearophile via Digitalmars-d-learn
Xinok: My concern is that SortedRange only accepts a range which is random-access and limits its functionality to those primitives. Concatenation is not required for random-access ranges, so should we expect SortedRange to overload this operator? I understand, that's why I am asking this her

Re: More flexible sorted ranges?

2014-11-02 Thread bearophile via Digitalmars-d-learn
Ola Fosheim Grøstad: Shouldn't sorted range maintain the invariant automatically in order to remain typesafe? Yes, of course. Bye, bearophile

More flexible sorted ranges?

2014-11-02 Thread bearophile via Digitalmars-d-learn
I have often arrays that are sorted, and sometimes I'd like to append items to them. So I'd like to write something like: SortedRange!(Foo[], q{ a.x < b.x }) data; data ~= Foo(5); immutable n = data.upperBound(Foo(2)).length; This means having an array of Foos as sorted range, and appending

Re: Need help: Return reference slice

2014-10-30 Thread bearophile via Digitalmars-d-learn
Steven Schveighoffer: long a = src.countUntil(start); if (a < 0) return src; // null a += start.length; long b = src[a..$].countUntil(end); I think there it's better to use "auto" instead of "long". Bye, bearophile

Re: Need help: Return reference slice

2014-10-29 Thread bearophile via Digitalmars-d-learn
advibm: I would like to have something like that: char[] buf; // already filled array char[] partOfBuf = betweenTwoStrings(buf, "START", "END"); partOfBuf[0] = 'a'; // THIS should also change the 'buf' variable assert(buf[0] == 'a'); Thanks for your help To do this you don't need to return

Re: Two cases for improving error messages

2014-10-25 Thread bearophile via Digitalmars-d-learn
Shriramana Sharma: int i ; ref ir = i ; // Error: variable ref_type.main.ir only parameters or foreach declarations can be ref // Comment: add ", return values" after "parameters" } I like this. Bye, bearophile

Re: classInstanceSize and vtable

2014-10-23 Thread bearophile via Digitalmars-d-learn
Etienne Cimon: So what's the point of making a class or methods final? It forbids subclassing. And final methods are not virtual, so they can be inlined. Bye, bearophile

Re: classInstanceSize and vtable

2014-10-23 Thread bearophile via Digitalmars-d-learn
Etienne Cimon: I'm not sure, why does a final class carry a vtable pointer? In D all class instances contain a pointer to the class and a monitor pointer. The table is used for run-time reflection, and for standard virtual methods like toString, etc. Bye, bearophile

Re: Constructor params with same name as members

2014-10-23 Thread bearophile via Digitalmars-d-learn
Jonathan M Davis: Questions like this have come up and been discussed before, but using the same parameter names as member variable names for constructors is such a common practice that there would be quite a bit of screaming if we didn't allow it. I'm willing to hear them scream. D should s

Re: Sorting array of string arrays by an element in the string array

2014-10-22 Thread bearophile via Digitalmars-d-learn
Neal: Interesting! Thank you. Memory isn't a problem Unfortunately currently the sort-decorate-undercorate in Phobos is not very fast. but I would still like to learn how to write more efficient programs. If i posted my code would you be able to give me some advice? There is far more th

Re: Sorting array of string arrays by an element in the string array

2014-10-22 Thread bearophile via Digitalmars-d-learn
neal: data.sort!q{ to!int(a[4]) > to!int(b[4]) }; This code fixes my problem! Thanks for the quick responses guys. you rock! That converts string->int many more than once for each string. So if memory is not a problem, consider using a decorate-sort-undecorate pattern: data.schwartzSort!

Re: Sorting array of string arrays by an element in the string array

2014-10-21 Thread bearophile via Digitalmars-d-learn
neal: Anybody have any suggestions? Something like this, perhaps? data.sort!q{ a[4] > b[4] }; Bye, bearophile

Re: Global const variables

2014-10-21 Thread bearophile via Digitalmars-d-learn
Szymon Gatner: const int[] a; int[] b; static this() { b = [1]; a = b; } Ant this code works? What is the point of const then if you can assign it to mutable slice? It works, and I think it should work. Inside the (module) constructor the const state is handled differently. Thank

Re: Global const variables

2014-10-21 Thread bearophile via Digitalmars-d-learn
Minas Mina: Aren't pure functions supposed to return the same result every time? If yes, it is correct to not accept it. But how can main() not be pure? Or, how can't the 'a' array be immutable? Bye, bearophile

Global const variables

2014-10-21 Thread bearophile via Digitalmars-d-learn
Currently this code gets rejected: const int[] a = [1]; void main() pure { auto y = a[0]; } test2.d(3,14): Error: pure function 'D main' cannot access mutable static data 'a' test2.d(3,14): Error: pure function 'D main' cannot access mutable static data 'a' But is this a good idea? Isn'

Re: Removing whitespace duplicates

2014-10-21 Thread bearophile via Digitalmars-d-learn
Nordlöw: It would be nice to have a lambda-variant of std.string.tr to call like x.tr!isWhite(['_']) If your text is ASCII, then there is std.ascii.whitespace that can be given as argument to std.string.tr. Bye, bearophile

Re: Removing whitespace duplicates

2014-10-20 Thread bearophile via Digitalmars-d-learn
Justin Whear: std.string.squeeze might be more appropriate. But with tr you can also replace the spaces with the underscore. Bye, bearophile

Re: Removing whitespace duplicates

2014-10-20 Thread bearophile via Digitalmars-d-learn
Nordlöw: How can I extend string line = "carwash"; line.strip.splitter!isWhite.joiner("_").to!string so that car wash becomes car_wash and not car___wash ? Use std.string.tr. Bye, bearophile

Re: Benchmark games, Rust, big ints and Pi

2014-10-20 Thread bearophile via Digitalmars-d-learn
John Carter: Your paste has expired / no longer there but the subject has come up again... ... Do you still have your implementation hanging around? I think it was this. *Untested*: void main(string[] args) { import core.stdc.stdio, std.bigint, core.stdc.stdlib; immutable n = (

Re: Beginner ?. Why does D suggest to learn java

2014-10-17 Thread bearophile via Digitalmars-d-learn
Ola Fosheim Grøstad: The IDE support is probably a bit better with Java/C# The importance of the IDE for the first language is controversial. I think it's not so important. and using a statically typed language as your first language has advantages, While no one has determined scientifi

Re: Beginner ?. Why does D suggest to learn java

2014-10-16 Thread bearophile via Digitalmars-d-learn
RBfromME: I'm a newbie to programming and have been looking into the D lang as a general purposing language to learn, yet the D overview indicates that java would be a better language to learn for your first programming language. Why? Looks like D is easier than Java... Python is probably

Re: How to apply a function to a container/array ?

2014-10-15 Thread bearophile via Digitalmars-d-learn
Domingo: Ideally I want to use something like this: - import std.stdio; import std.string; import std.algorithm; import std.conv; void main() { string[] ar = [" dad ", " blue "]; writeln(typeid(ar)); //ar.each(writeln); //ar.map!writeln;

Re: is there any hack to determine if variable is __gshared?

2014-10-13 Thread bearophile via Digitalmars-d-learn
ketmar: is there any hack/trick to determine if variable is __gshared? or if it is a thread-local, for that matter? There is the -vtls compiler switch. Bye, bearophile

Re: Formatted output of range of tuples

2014-10-13 Thread bearophile via Digitalmars-d-learn
Ali Çehreli: foreach (i, element; MyRange(42).enumerate) { // ... } versus sequence!"n" and zip: foreach (i, element; zip(sequence!"n", MyRange(42))) { // ... } But it's better to not use automatic unpacking of tuples. See issues 7361 and especially 9817. B

Re: return types of std.functional functions

2014-10-12 Thread bearophile via Digitalmars-d-learn
yawniek: i found two snippets from the functional docs that do not work (anymore?) http://dlang.org/phobos/std_functional.html assert(compose!(map!(to!(int)), split)("1 2 3") == [1, 2, 3]); and int[] a = pipe!(readText, split, map!(to!(int)))("file.txt"); throwing a std.array.array into the

Re: Byte Array Literal

2014-10-09 Thread bearophile via Digitalmars-d-learn
ketmar: additionally to all bearophile said, there is another interesting thing in D: special string literals for hex data. immutable ubyte[] n = cast(typeof(n))x"deadf00d"; or even: immutable ubyte[] n = cast(typeof(n))x"de ad f 0 0 d"; spaces doesn't matter, only digits do. The prob

Re: dupping to allow vector operation?

2014-10-09 Thread bearophile via Digitalmars-d-learn
Marc Schütz: It's equivalent to: int[] tmp = a1[] * 3; int[] a4 = tmp.dup; The first part is of course identical to line 3, so this should be an error, too. Normal rules for evaluation order require `a1[] * 3` to be evaluated before `(...).dup`, so where is it supposed to store the

Re: Byte Array Literal

2014-10-09 Thread bearophile via Digitalmars-d-learn
You want ubytes (unsigned bytes) because 0x04 is 164 that is bigger than byte.max. I'd like bytes to be named sbyte and ubyte in D, but Walter has refused this. Bye, bearophile

Re: Byte Array Literal

2014-10-09 Thread bearophile via Digitalmars-d-learn
Anibal: byte[] arr = [ 0x00, 0xA4, 0x04]; This throws a int[] to byte[] cast error You want ubytes (unsigned bytes) because 0x04 is 164 that is bigger than byte.max. So use: ubyte[] arr = [ 0x00, 0xA4, 0x04]; I also tried byte[] arr = [cast(byte) 0x00, cast(byte)0xA4, cast(byte) 0x04];

dupping to allow vector operation?

2014-10-09 Thread bearophile via Digitalmars-d-learn
Observe: void main() { int[3] a1 = [1, 3, 6]; int[] a2 = a1[] * 3; // line 3, Error int[] a3 = a1.dup[] *= 3; // line 4, OK? int[] a4 = (a1[] * 3).dup; // line 5, Error } Currently the operation in line 4 is accepted: test.d(3,17): Error: array operation a1[] * 3

Re: Formatted output of range of tuples

2014-10-08 Thread bearophile via Digitalmars-d-learn
anonymous: You can turn the tuples into ranges with `only`: writef("%(%(%s %)\n%)", zip(indexes, source).map!(t => only(t.expand))); This is a nice idea. Expand can probably be replaced by a []. I presume this works only if the types inside the tuple are the same. Bye, bearophile

Re: Formatted output of range of tuples

2014-10-08 Thread bearophile via Digitalmars-d-learn
antropod: Looks fairly straightforward. But, the second function causes compilation error: std.format.FormatException@C:\D\dmd2\windows\bin\..\..\src\phobos\std\format.d(2 585): Expected '%s' format specifier for type 'Tuple!(uint, uint)' Can you help me with that? Currently the "%(%s%)"

Re: coding practices: include whole module or only the needed function

2014-10-06 Thread bearophile via Digitalmars-d-learn
AsmMan: import myModule : func, func2; I use this in D to know what I have imported and where is was imported from. Bye, bearophile

Re: A hash table implementation benchmark

2014-10-01 Thread bearophile via Digitalmars-d-learn
Ali Çehreli: Never mind then. Well, now the D code is present, so why don't you benchmark it (but I don't know how much correct it is)? :-) Bye, bearophile

Re: A hash table implementation benchmark

2014-10-01 Thread bearophile via Digitalmars-d-learn
Ali Çehreli: Found on Reddit: Where's the Reddit thread? Are you motivated enough to compare D's associative arrays with those results? :) D associative arrays are often even slower than CPython ones, so I don't expect D to shine in this comparison. This is a D port of the Java code, b

Re: Can I make a variable public and readonly (outside where was declared) at same time?

2014-09-26 Thread bearophile via Digitalmars-d-learn
Marc Schütz: Alternatively, you could create a union with a private and a public member with the same types, but I wouldn't recommend it. Besides, the members would need to have different names: class Foo { union { private int a; public int b; }

Re: enum-indexed arrays

2014-09-20 Thread bearophile via Digitalmars-d-learn
Nordlöw: should be Enumerator start = Enumerator.min This also requires the enum to have adjacent values (in general enums can skip values). Bye, bearophile

Re: enum-indexed arrays

2014-09-20 Thread bearophile via Digitalmars-d-learn
Nordlöw: Have anybody thought about adding safe enum-based indexing to builtin arrays? Ada has this. I'd like this. I'd like even more: a general way to have optionally strongly typed array indexes. enum I { a=3,b=4,c=5 } int[I] x = [3,4,5]; In D currently that "int[I]" is an as

Re: Are void arrays usable ?

2014-09-20 Thread bearophile via Digitalmars-d-learn
Take a look in bugzilla, if it's not already present file it. https://issues.dlang.org/show_bug.cgi?id=13505 Bye, bearophile

Re: Are void arrays usable ?

2014-09-20 Thread bearophile via Digitalmars-d-learn
badlink: Does this mean that void arrays are a thing or it is a bug ? You can compile that with: class Foo { void[10] x = void; } But this code shows a dmd bug (lack of line number): class Foo { void[10] x; } void main() {} Error: void does not have a default initializer Take a

Re: String[] pointer to void* and back

2014-09-18 Thread bearophile via Digitalmars-d-learn
anonymous: Here, the pointer to the stack escapes the function. Don't do that! Hopefully the D type system will be improved with scoping tracking & management, to turn similar operations into compilation errors (as in Rust, but perhaps in a less refined way). Bye, bearophile

Re: GC-less Hash-Tables (AA)

2014-09-17 Thread bearophile via Digitalmars-d-learn
H. S. Teoh: How do you implement a completely GC-free AA with no limit on number of entries stored? Ada2012 has a fixed-size hash in the standard library, it can even be allocated on the stack. But the number of entries is not unlimited. Bye, bearophile

Re: switch statement exiting a void function

2014-09-16 Thread bearophile via Digitalmars-d-learn
Jonathan: This is not intended. Note that calling "return;" after "funi(...)" makes everything work. However, it feels like I'm doing something wrong here? Try: enum RunOpt { opt1, opt2, opt3 } // No semicolon here final switch (option) with (RunOpt) { case opt1: fun1(...); break;

Re: Why do 'abstract' methods with 'in' or 'out' contracts require a body?

2014-09-13 Thread bearophile via Digitalmars-d-learn
Marc Schütz: "Functions declared as abstract can still have function bodies. This is so that even though they must be overridden, they can still provide ‘base class functionality.’" => it's intentional But also they can not have. I don't think it's intentional. I think it's a temporary lim

Re: std.algorithm.reduce on an array of structs

2014-09-11 Thread bearophile via Digitalmars-d-learn
Daniel Kozak: You can just use min: import std.stdio, std.algorithm; struct Thing { uint x; alias x this; } alias minimum = reduce!min; void main() { immutable ar1 = [10, 20, 30, 40, 50]; ar1.minimum.writeln; immutable ar2 = [Thing(10), Thing(20), Thing(40)];

Re: A significant performance difference

2014-09-01 Thread bearophile via Digitalmars-d-learn
ketmar: But I think the "j = x.byKey.front; p = x.byValue.front;" code looks sufficiently idiomatic, and its performance is terrible. that's why i suggest to extend AA API, adding x.firstKey and x.firstValue functions. i'll try to make the patch soon. In theory the best solution is to impr

Re: A significant performance difference

2014-09-01 Thread bearophile via Digitalmars-d-learn
It seems fit for a performance bug report. I have to create a synthetic benchmark that shows just the problem. https://issues.dlang.org/show_bug.cgi?id=13410 (Perhaps I have credited the wrong person there, sorry, I will fix). Bye, bearophile

Re: A significant performance difference

2014-09-01 Thread bearophile via Digitalmars-d-learn
ketmar: Thank you for your analysis and code. while (x.length) { foreach (key; x.keys) { auto pp = key in x; if (pp is null) continue; j = key; p = *pp; x.remove(j); This is a little cleaner: while (x.lengt

Re: Possible difference in compilers?

2014-09-01 Thread bearophile via Digitalmars-d-learn
Charles: My solution I came up with (and works locally) is: import std.stdio; void main() { int height=1,t=1,oldN=0,n; readf(" %d\n", &t); foreach (i;0 .. t) { readf(" %d\n", &n); foreach (j; oldN .. n) I suggest to add a blank line after the import, to move t

Re: How to compare two types?

2014-08-31 Thread bearophile via Digitalmars-d-learn
Adam D. Ruppe: If you want to compare the runtime type of a class object, you can do: if(typeid(obj_one) == typeid(obj_two)) that should tell you if they are the same dynamic class type. And what about: if (is(typeof(obj_one) == typeof(obj_two))) Bye, bearophile

A significant performance difference

2014-08-31 Thread bearophile via Digitalmars-d-learn
This is C++ code that solves one Euler problem: -- #include #include const unsigned int H = 9, W = 12; const int g[6][3] = {{7, 0, H - 3}, {1 + (1 << H) + (1 << (2 * H)), 0, H - 1}, {3 + (1 << H), 0, H - 2}, {3 + (2 <<

Re: I can ask questions about dmd on windows here in this forum?

2014-08-31 Thread bearophile via Digitalmars-d-learn
Ali Çehreli: Unless there is a specific reason not to, use 'string'. When you really need random access to characters, then use 'dstring'. So are the use cases for wstring limited? Bye, bearophile

Re: literate programming in D

2014-08-29 Thread bearophile via Digitalmars-d-learn
nikki: I use it to change my d sourcefile slightly (into valid markdown) then I use a node module (ghmd) to make sortof sexy html from that. Are you going to add popups of the types as in the F# page I have linked? Bye, bearophile

Re: Issue with dmd 2.066, alias this, and sort

2014-08-27 Thread bearophile via Digitalmars-d-learn
rcor: I've tried to express my problem in a mostly minimal example here: https://gist.github.com/murphyslaw480/d4a5f857a104bcf62de1 The class Point has an alias this to its own property 'feature()', which returns a reference to a private member. When I try to sort a Point[], DMD fails with "

Re: literate programming in D

2014-08-26 Thread bearophile via Digitalmars-d-learn
nikki: I've been googling without luck, is there a way to do literate programming in D? D1 had built-in support for literate programming, but it was removed from D2 because it was regarded as not useful enough: http://digitalmars.com/d/1.0/html.html I find literate Haskell programs all the

Re: Are there any exercises/challenges for D?

2014-08-26 Thread bearophile via Digitalmars-d-learn
maik klein: Are there any exercises/challenges for D? Some exercises here: http://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_D Please announce them here when you solve some of them :-) Bye, bearophile

Re: Error with constraints on a templated fuction

2014-08-25 Thread bearophile via Digitalmars-d-learn
Jeremy DeHaan: It compiles if I remove the 'if(typeof(T) is dchar)' section. Any thoughts? Try: if (is(T == dchar)) Bye, bearophile

Re: unclear compile error for struct with string template

2014-08-25 Thread bearophile via Digitalmars-d-learn
Oleg B: [code] void doSome(size_t N, T, string AS)( vec!(N,T,AS) v ) { } struct vec(size_t N, T, string AS) { T[N] data; } void main() { doSome( vec!(3,float,"xyz")([1,2,3]) ); } [/code] compile with new dmd v2.066.0 and get error: Error: template opbin.doSome(ulong N, T, string AS)(vec!(N, T,

Re: Why no multiple-dispatch?

2014-08-24 Thread bearophile via Digitalmars-d-learn
Aerolite: I was surprised to learn yesterday that D does not actually support Multiple-Dispatch, also known as Multimethods. Why is this? Support for this feature is already present in Scala, C# 4.0, Groovy, Clojure, etc... Would it not make sense for D to remain competitive in this regard? I

Re: Are there any exercises/challenges for D?

2014-08-24 Thread bearophile via Digitalmars-d-learn
Ola Fosheim Grøstad: Bearophile has created many such examples at Rosettacode. I am updating and improving them, but I have created only a percentage of them (60-70%? I don't know). Bye, bearophile

Re: Are there any exercises/challenges for D?

2014-08-24 Thread bearophile via Digitalmars-d-learn
maik klein: Are there any exercises/challenges for D? Something like this? http://www.haskell.org/haskellwiki/99_questions/1_to_10 This is an interesting question. There are many exercises/challenges that can be done in D, but I don't know any specific for D. As D challenge I suggest to wr

Re: Foreach/opApply with @nogc

2014-08-24 Thread bearophile via Digitalmars-d-learn
ketmar: so it can be forgotten in Bugzilla. ;-) And in ten, or one hundred or one thousand years the whole D language will be forgotten. There are various levels of remembering and forgetting. Putting bugs and ERs in databases is a different kind of forgetting. Bye, bearophile

Re: Foreach/opApply with @nogc

2014-08-24 Thread bearophile via Digitalmars-d-learn
ketmar: but i tend not to fill enhancement requests without corresponding patches, I agree that having a patch ready is much better. But people like me file hundreds of ERs without too much damage done, and many of them get eventually implemented. If you find a D limitation, then putting th

Re: Foreach/opApply with @nogc

2014-08-24 Thread bearophile via Digitalmars-d-learn
ketmar: there is currenly no way to specify attributes for such implicit delegates. It could be a nice language enhancement. Bye, bearophile

Re: How to get nogc to work with manual memory allocation

2014-08-24 Thread bearophile via Digitalmars-d-learn
Bienlein: @nogc is meant mostly for stack-allocation. Ah, I missed that. Thanks for telling me. @nogc is also for allocation from the C heap, despite this is less common :-) Bye, bearophile

Re: D1: Error: duplicate union initialization for size

2014-08-24 Thread bearophile via Digitalmars-d-learn
jicman: This is line 7634: const Size DEFAULT_SCALE = { 5, 13 }; What does the error say and how can I fix it? Thanks. Can you show the (reduced) definition of Size and DEFAULT_SCALE? Even better to show a minimized self-contained program that has the problem. Bye, bearophile

Re: How to get nogc to work with manual memory allocation

2014-08-24 Thread bearophile via Digitalmars-d-learn
Bienlein: Is there a way to get around this? Perhaps there are ways, but note that @nogc is meant mostly for stack-allocation. In general when in D you have to write lot of hairy code to do something, it means that in most cases you shouldn't do that something. When calling delete t the

Re: 'idiomatic' porting of c and or c++ code that does NULL checking

2014-08-23 Thread bearophile via Digitalmars-d-learn
ketmar: don't use '==' to check for nulls. the right way is: if (foo is null) {} if (bar !is null) {} '==' transforms to opEquals call (see 'operator overloading') and 'is' not. I use "is" and "!is" for class references and == != for pointers. But now I think you are right, and in D it

Re: 'idiomatic' porting of c and or c++ code that does NULL checking

2014-08-23 Thread bearophile via Digitalmars-d-learn
nikki: How would you write it? I don't know how much idiomatic this is, but you can start cleaning up the code: - Renaming the function with something more clear; - using a D enumeration for the various constants. - I have used a "." before the module-level variables to denote better they a

Re: BitArray - preview of what's to come?

2014-08-22 Thread bearophile via Digitalmars-d-learn
Suliman: bool[4] x = [1, 1, 0, 0]; BitArray ba = BitArray(x); When I try to compile this I am getting error: source\app.d(13): Error: cannot implicitly convert expression (x) of type bool[4] to uint What I am doing wrong? It still lacks some features like a constructor that accepts a (l

Re: D with no druntime

2014-08-22 Thread bearophile via Digitalmars-d-learn
Marc Schütz: But it would need to halt the system of course, because throwing a RangeError might not work in his minimalistic environment. Halting the system, or jumping to a error routine seems better than running in undefined state. Bye, bearophile

Re: How I can iterate data in structure

2014-08-22 Thread bearophile via Digitalmars-d-learn
Suliman: foreach (field; result.tupleof) Why I should here specify type of iterable element, but not first element that I use for iteration? I mean: foreach (_some_type_possible_enum_ field; result) ? I don't understand your question. In my code I have not specified types in the foreach

Re: How I can iterate data in structure

2014-08-22 Thread bearophile via Digitalmars-d-learn
Suliman: void main() { auto result = readconfig(); foreach (_; result) { // I want to iterate result that I got from structure. } } auto readconfig() { struct ConfigStruct { string key1; st

Re: goto skips declaration of variable

2014-08-19 Thread bearophile via Digitalmars-d-learn
nrgyzer: Sure, I can also use nested functions, but in my opinion it results in dirty and complex code. It's totally overkilled compared to a simple if and goto-instruction. Often nested functions are less complex, more clean and simpler code compared to using gotos. I suggest to start using

Re: goto skips declaration of variable

2014-08-18 Thread bearophile via Digitalmars-d-learn
It looks like a compiler bug https://issues.dlang.org/show_bug.cgi?id=13321 Bye, bearophile

Re: goto skips declaration of variable

2014-08-18 Thread bearophile via Digitalmars-d-learn
nrgyzer: import std.bigint; void main(string[] args) { BigInt i = "12345"; if (args.length > 1) { goto Exit; } i = BigInt("67890"); Exit: return; } When I try to compile this sample application I'm getting the foll

Re: Static function at module level

2014-08-18 Thread bearophile via Digitalmars-d-learn
H. S. Teoh: Is there a bug filed for this? Probably there is. But I stopped filing similar bugs because they seem to have a very low priority. Bye, bearophile

Re: Static function at module level

2014-08-17 Thread bearophile via Digitalmars-d-learn
ketmar: other function declarations (methods, nested functions) accepts 'static', so why free functions shouldn't? For various reasons, one of them is that accepting useless code confuses newbies and doesn't allow them to build a correct model of the D semantics in their head. Bye, bearoph

Re: Nullable instantiator anyone?

2014-08-17 Thread bearophile via Digitalmars-d-learn
Nordlöw: I'm missing an instantiator function for std.typecons:Nullable. Is this is intentional? If not, is this Nullable!T nullable(T)(T a) { return typeof(return)(a); } sufficient for our needs? It could be sufficient, but note that in Phobos there are two different versions of Nulla

Re: A little of coordination for Rosettacode

2014-08-14 Thread bearophile via Digitalmars-d-learn
safety0ff: Here's a candidate for http://rosettacode.org/wiki/Extensible_prime_generator#D in case it is preferred to the existing entry: http://dpaste.dzfl.pl/43735da3f1d1 I was away. I have added your nice code with some small changes as an alternative faster version. I think you have com

Re: Very vague compiler error message

2014-08-14 Thread bearophile via Digitalmars-d-learn
Théo Bueno: Same issue here with dsfml-audio, this is really annoying :/ Have you filed the issue? Bye, bearophile

Re: What hashing algorithm is used for the D implementation of associative arrays?

2014-08-14 Thread bearophile via Digitalmars-d-learn
Marc Schütz: Isn't SuperFastHash vulnerable to collision attacks? D AAs used to be not vulnerable to collision attacks because they resolved collisions building a red-black tree for each bucket. Later buckets became linked lists for speed, leading to the current sensitivity to collision att

Re: Max/Min values in an associative array

2014-08-14 Thread bearophile via Digitalmars-d-learn
TJB: I am trying to find the max and min values in an associative array. Say I have: double[char] bids; bid['A'] = 37.50; bid['B'] = 38.11; bid['C'] = 36.12; How can I find the max and min values. I am thinking that I need to use max and min functions from std.algorithm, but not sure how to

Re: Is there a way to map associative arrays

2014-08-01 Thread bearophile via Digitalmars-d-learn
Freddy: uint[uint] test; void main(){ test=[0:2 ,1:3 ,2:4]; writeln(test.map!(a=>a-2)); } If you need keys or values you have .keys .values, .byKey, .byValue (the first two are eager). If you need both you are out of luck, and if you want to write safe code it's better to us

Re: memory/array question

2014-07-31 Thread bearophile via Digitalmars-d-learn
Eric: Thanks. That really works. I timed doing auto mySlice = ptr1[0 .. ptr2 - ptr1]; 1,000,000 times versus auto mySlice = ptr1[0 .. ptr2 - ptr1].dup; 1,000,000 times and I am quite convinced the data is not being copied. Take a look at the asm! Bye, bearophile

Re: Checked shift?

2014-07-31 Thread bearophile via Digitalmars-d-learn
H. S. Teoh: OK, makes sense. But what about if only the most significant bit is 1? Wouldn't that also be an overflow? So you're essentially checking if the topmost n bits are zero, where n is the number of bits you wish to shift by. Of course. https://issues.dlang.org/show_bug.cgi?id=13231

Re: memory/array question

2014-07-31 Thread bearophile via Digitalmars-d-learn
Eric: Suppose I have some memory allocated on the heap, and I have two pointers pointing to the beginning and end of a contiguous segment of that memory. Is there a way I can convert those two pointers to an array slice without actually copying anything within the segment? Use something li

Re: Unexpected memory reuse

2014-07-31 Thread bearophile via Digitalmars-d-learn
Marc Schütz: class buffer(T, size_t sz) { auto arr = new T[sz]; This allocates an array with `sz` elements once _at compile time_, places it somewhere into the executable, and uses its address as the default initializer for the member `arr`. Right. It's not a compiler bug. Dmd/ldc

Re: Checked shift?

2014-07-31 Thread bearophile via Digitalmars-d-learn
H. S. Teoh: What would you check for? Shifting something that already has its high bit set? If you have a uint where the 3 most significant bits are 1, and you shift it 3 bits on the left, you lose those three bits, you have an overflow. The point of checkedint functions/intrinsics is to re

Checked shift?

2014-07-31 Thread bearophile via Digitalmars-d-learn
Is it a good idea to add int/uint/long/ulong functions for the "<<" left shift operation here? https://github.com/D-Programming-Language/druntime/blob/master/src/core/checkedint.d Bye, bearophile

Re: Split class declaration and definition

2014-07-31 Thread bearophile via Digitalmars-d-learn
Kozzi11: Is possible to somehow split class declaration and definition. I mean something like this: class C { void hello(); // just prototype } class C { void hello() { //actual code } } or something like this void C.hello() { //actual code } I think this is cur

<    1   2   3   4   5   6   >