Re: Private struct constructor
On Thursday, 4 October 2018 at 09:21:39 UTC, Simen Kjærås wrote: This is apparently a known issue: https://issues.dlang.org/show_bug.cgi?id=18979 which is basically just a special case of this issue: https://issues.dlang.org/show_bug.cgi?id=2775 -- Simen I see. Looks like the chances of it being fixed anytime soon are slim. Thanks for the info.
Re: Private struct constructor
On Thursday, 4 October 2018 at 08:14:44 UTC, Simen Kjærås wrote: On Thursday, 4 October 2018 at 07:31:21 UTC, Ritchie wrote: Any reason why this works? https://run.dlang.io/is/TALlyw Yup. Alright, so there's a few features in use here - which one are you asking about? 1. Private constructor. You can call the private constructor because the unit of encapsulation in D is the module, not the type. So everything is visible to everything else inside the same module. 2. @disable this() This only disables default construction. Since you call a different constructor, this doesn't affect the compilation. 3. @disable this(this) This disables copy construction. In the example, no copying occurs - the variable declaration leads to a move instead. Simply put, copy construction requires that two copies exist simultaneously, and in this case the potential second copy is immediately destroyed, so no copy is necessary. 4. @disable void opAssign() There's several reasons this doesn't affect compilation here. First, the signature is wrong - you're disabling an opAssign that takes no arguments. You're probably wanting to do @disable void opAssign(X x);. Now, even that isn't going to cause it to fail to compile in this case though, since as in #3, what's happening on line 14 is move construction, not assignment. To force an assignment, you need to have an object already: X x = void; x = X(5); // calls opAssign So, now we've explained why it compiles. Currently, there's no way to @disable or hook move construction. There's a DIP in the works (DIP 1014) that aims to provide a hook into move construction, but I don't see that it allows for @disabling it altogether. Hope this helps! -- Simen I apologize for not making it clear. I was talking about the private constructor only. The @disable this() is there to prevent struct literal syntax and the other disables really have no reason to be there for the purpose of this question. Oddly enough I asked this because I was working on something and was able to call the private constructor from another module, but then I created the run.dlang.io snippet to demo my problem. I have this in one module: https://pastebin.com/J8r4fyK8 and this in another module: void testUniquePtr() { import bclib.memory.unique_ptr : Unique; alias TestUnique = Unique!(int, TestMallocator); { auto unique = TestUnique(20); assert(*unique == 20); } TestMallocator.check(); } and it runs without complaints. (SmartPtrMembers doesnt have any constructors in it)
Re: Private struct constructor
On Thursday, 4 October 2018 at 07:55:48 UTC, Andrea Fontana wrote: On Thursday, 4 October 2018 at 07:31:21 UTC, Ritchie wrote: Any reason why this works? https://run.dlang.io/is/TALlyw Why not? The constructor is private.
Private struct constructor
Any reason why this works? https://run.dlang.io/is/TALlyw
Delegates with stackpointers
How does a delegate with a stackpointer work? e.g. in this example: https://run.dlang.io/is/XviMSl Does the second call to foo not overwrite the stack of the first call and thereby the data pointed to by bar1? How is that data preserved?
Improper display of Cyrillic in `pragma (msg, ...)` on Windows
Hi, To view Cyrillic CMD on Windows can be used `std.process.executeShell("chcp 65001 ");` and it works. What should I use to change the encoding to UTF-8 to the compiler messages in `pragma(msg, ...)` on Visual D? // import std.stdio, std.process; void main() { executeShell("chcp 65001"); writeln("Привет, мир!"); // Привет, мир! -> OK pragma(msg, "Привет, мир!"); // Привет, РјРёСЂ! -> wrong } // PS C++ supports the following directive in Visual Studio: https://msdn.microsoft.com/en-us/library/mt708823.aspx
Re: to auto or not to auto ( in foreach )
On Saturday, 16 July 2016 at 14:00:56 UTC, dom wrote: foreach(auto v; msg) writeln(v); gives an error that a basic type is expected foreach(v; msg) writeln(v); works .. but why? `Note: The ForeachTypeAttribute is implicit, and when a type is not specified, it is inferred. In that case, auto is implied, and it is not necessary (and actually forbidden) to use it.` http://dlang.org/spec/statement.html#ForeachStatement
Re: Higher Order Range Pattern
On Monday, 22 June 2015 at 15:25:12 UTC, Steven Schveighoffer wrote: On 6/22/15 11:04 AM, Dennis Ritchie wrote: Hi, I recently came across the following code: http://wiki.dlang.org/Higher_Order_Range_Pattern I can't understand why the properties and methods of the structure are called in the correct order. Why are the property `back()` and the method `popBack()` are not called even once? Because std.algorithm.equal does not use back or popBack. In general, please explain how it all works. I have a feeling you are not understanding something. This code is pretty straightforward, I don't know what else to explain about it. -Steve Thanks. I understand everything, just std.algorithm.equal introduced me to the great confusion :) Now everything fell into place.
Higher Order Range Pattern
Hi, I recently came across the following code: http://wiki.dlang.org/Higher_Order_Range_Pattern I can't understand why the properties and methods of the structure are called in the correct order. Why are the property `back()` and the method `popBack()` are not called even once? In general, please explain how it all works. ``` import std.stdio, std.range; struct Retro(Range) { @property { auto ref front() { debug writeln(back); return range_.back; } auto ref back() { debug writeln(front); return range_.front; } bool empty() { debug writeln(empty); return range_.empty; } } void popFront() { debug writeln(popBack); range_.popBack(); } void popBack() { debug writeln(popFront); range_.popFront(); } Range range_; } auto retro(Range)(Range range) { return Retro!Range(range); } void main() { import std.algorithm; auto arr = [1, 2, 3, 4, 5]; assert(equal(retro(arr), [5, 4, 3, 2, 1])); } ``` http://rextester.com/FMPGS76502
Re: fast way to insert element at index 0
On Tuesday, 23 June 2015 at 05:16:23 UTC, Assembly wrote: What's a fast way to insert an element at index 0 of array? now that the code is working I want to clean this: void push(T val) { T[] t = new T[buffer.length + 1]; t[0] = val; t[1 .. $] = buffer; buffer = t; } I did this because I didn't find any suble built-in data structure that let me insert an item into a specific index at first search. Slist does have insertFron(), exactly what I'm looking for it's a linked list. I think you want to do something like this: void main() { import std.algorithm; auto a = [1, 2, 3]; int val = 5; a = val ~ a; // vector.pushFront(); assert(equal(a[], [5, 1, 2, 3])); }
Re: How to avoid multiple spelling `import`
On Tuesday, 16 June 2015 at 12:41:14 UTC, Daniel Kozák wrote: On Tue, 16 Jun 2015 11:45:22 + Dennis Ritchie via Digitalmars-d-learn digitalmars-d-learn@puremagic.com wrote: I just want to import individual features of these modules. mixin template include(w...) { mixin _include!(w.length - 1, w); } mixin template _include(long N, i...) { mixin(import ~ i[N] ~ ;); mixin _include!(N - 1, i); } mixin template _include(long N : 0, i...) { mixin(import ~ i[N] ~ ;); } mixin include!( std.stdio : writeln, write, std.conv : to ); void main() { writeln(to!string(7)); } Thanks. Maybe I'll use this code in your own programs. I still believe that this design deserves existence in D: https://issues.dlang.org/show_bug.cgi?id=14704
How to avoid multiple spelling `import`
Hi, I can write this: import std.range : chain, split; But I can not write this: import std.range : chain, split, std.algorithm : map, each; We have several times to write the word `import`: import std.range : chain, split; import std.algorithm : map, each; Does D something to solve this problem? Maybe there is something like: import std.range{chain, split}, std.algorithm{map, each}; import std.range(chain, split), std.algorithm(map, each); import { std.range : chain, split; std.algorithm : map, each; }
Re: How to avoid multiple spelling `import`
On Tuesday, 16 June 2015 at 11:16:32 UTC, Idan Arye wrote: There is no problem to be solved here. Having to type `import` for each imported module is not big enough a burden to justify this additional syntax. No, I think it is a holdover from C++-times — to write `import` for each new header file. For example, this feature is implemented Go: import ( os bufio strings fmt )
Re: How to avoid multiple spelling `import`
Maybe not everyone needs these features. But, unfortunately, I often use a lot of imported modules. And use every time the word `import` very bad. version (none) { import std.math, std.conv, std.stdio, std.ascii, std.range, std.array, std.regex, std.format, std.bigint, std.traits, std.random, std.string, std.numeric, std.variant, std.typecons, std.container, std.algorithm, std.typetuple, std.exception, core.checkedint; } I just want to import individual features of these modules.
Re: appender!(dchar[]) put fail
On Saturday, 13 June 2015 at 13:32:19 UTC, kerdemdemir wrote: One more question I am asking those kind of questions to understand and not ask same stuff over and over, : auto totalStr = chain(stringB.replicate(bCount), stringC.replicate(cCount)); writeln(typeof(totalStr.array()).stringof); dchar[] But auto totalStr = chain(stringB.repeat(bCount), stringC.repeat(cCount)); writeln(typeof(totalStr.array()).stringof); dchar[][] It seems to me a little inconsistent. range.repeat and array.replicate gives result in difference dimension. Is there any explanation or logic that I am missing which results this behaviour? std.range.repeat is a lazy version unlike std.array.replicate: 5.repeat(3).writeln; // a lazy version // [5, 5, 5] [5].replicate(3).writeln; // [5, 5, 5] // but [5].repeat(3).writeln; // a lazy version // [[5], [5], [5]]
Re: appender!(dchar[]) put fail
On Saturday, 13 June 2015 at 13:01:29 UTC, kerdemdemir wrote: Sorry to making the discussion longer and wasting your times. But I am looking for a way without for loops. Also looping every element one by one does not seems very efficient to me. Any advices for that? Maybe it fit? auto stringB = readln.chomp.map!(to!dchar).array; auto stringC = readln.chomp.map!(to!dchar).array; auto charAppender = appender!(dchar[][]); auto totalStr = stringB.repeat(3).chain(stringC.repeat(5)); charAppender.put(totalStr); writeln(charAppender); charAppender.put(cd.dup); charAppender.put(testd.dup); writeln(charAppender);
Re: char[][] to std::vectorstd::string - DIP or dmd-issue?
On Saturday, 13 June 2015 at 15:45:34 UTC, anonymous wrote: Please show an example of .dup you'd like to avoid. For example, if you need to create a five-dimensional array of strings :)
Re: char[][] to std::vectorstd::string - DIP or dmd-issue?
On Saturday, 13 June 2015 at 16:20:46 UTC, anonymous wrote: Do you like to write? char[][] strArray = [foo.dup, bar.dup, baz.dup]; Ok. That's all you're on about? Basically you'd like this: char[] s = foo; and this: char[][] a = [[foo]]; etc. Yes. That's right, and not otherwise :) Yeah, that would be neat. But typing out .dup isn't that bad, and converting a `string[]` to a `char[][]` is simple: import std.conv: to; auto a = [foo].to!(char[][]); Yes, but it is not suitable for multidimensional array of strings. I suggest that such an option: str[] strArray = [foo, bar, baz]; I don't see how adding a new builtin type `str` would solve anything. And why in C++ is running `std::vectorstd::string` ? Really in D can not do something like that? Maybe a new type will not solve anything, but there should be other ways to do in D analogue strings of C++. On Saturday, 13 June 2015 at 16:22:44 UTC, anonymous wrote: I don't understand what you're trying to say with that quote. I would not say `simpler`, and `basic`. I just forgot the right word, because my English is not good enough.
char[][] to std::vectorstd::string - DIP or dmd-issue?
Hello, everyone! I like to work with arrays of strings like `string[] strArray`, but unfortunately, they are immutable. I do not like to work with arrays of strings such as `char[][] strArray`, because it is necessary to apply the method .dup each substring to make them work :) I understand that the type of `string[]` to D is a simple data type than `char[][]`, but it seems to me that the problem is solved in C++: std::vectorstd::string stdArray; I wish to propose the creation of new types of data D: str, wstr, dstr, which will be the analogs of C++ `std::vectorstd::string`. I do not know whether it is possible to create in the D, but I want to know where I write a sentence? Can I file a dmd-issue, or should I create a DIP, because it is too big improvement?
Re: char[][] to std::vectorstd::string - DIP or dmd-issue?
On Saturday, 13 June 2015 at 15:45:34 UTC, anonymous wrote: Before jumping to a solution, please elaborate on the perceived problem. I have a feeling that there is none. Do you like to write? char[][] strArray = [foo.dup, bar.dup, baz.dup]; I suggest that such an option: str[] strArray = [foo, bar, baz]; On Saturday, 13 June 2015 at 15:38:31 UTC, Dennis Ritchie wrote: Ie str, wstr, dstr be mutable counterparts immutable strings respectively str (mutable(char[])), wstr (mutable(wchar[])), dstr (mutable(dchar[])). In C++: std::vectorstd::string std::string in C++. str[], wstr[], dstr[] in C++: std::vectorstd::vectorstd::string std::vectorstring in C++.
Re: char[][] to std::vectorstd::string - DIP or dmd-issue?
On Saturday, 13 June 2015 at 15:45:34 UTC, anonymous wrote: Huh? You mean with string literals? That would be a rather silly reason to avoid `char[]`. Please show an example of .dup you'd like to avoid. Yes, string literals. I understand that the type of `string[]` to D is a simple data type than `char[][]`, Are you saying that `string[]` is simpler than `char[][]`? That's not true: `string` is an alias for `immutable(char)[]`, so `string[]` is the same as `immutable(char)[][]`. On Monday, 18 May 2015 at 13:14:38 UTC, Steven Schveighoffer wrote: But really, a string is immutable. There's not a way around that. A string is the most basic level of array primitive, not even mutable arrays of non-char types have that, and it's an annoyance. From there, you have to build the data out of ROM into the heap. http://forum.dlang.org/post/mjctql$j19$1...@digitalmars.com
Re: char[][] to std::vectorstd::string - DIP or dmd-issue?
On Saturday, 13 June 2015 at 15:21:19 UTC, Dennis Ritchie wrote: I wish to propose the creation of new types of data D: str, wstr, dstr, which will be the analogs of C++ `std::vectorstd::string`. Ie str, wstr, dstr be mutable counterparts immutable strings respectively str (mutable(char[])), wstr (mutable(wchar[])), dstr (mutable(dchar[])). In C++: std::vectorstd::string str[], wstr[], dstr[] in C++: std::vectorstd::vectorstd::string
Re: char[][] to std::vectorstd::string - DIP or dmd-issue?
On Saturday, 13 June 2015 at 18:15:30 UTC, Dennis Ritchie wrote: Actually, I will file issue `std.conv` in Phobos to add such specifications. It will suit me. *specializations
Re: char[][] to std::vectorstd::string - DIP or dmd-issue?
On Saturday, 13 June 2015 at 17:39:25 UTC, Kagamin wrote: Type is probably possible, though conversion method will be simpler. You can even try to write a specialization of `to` for multidimentional arrays if it doesn't work. It appears the problem can be solved by creating specifications .to!strArray, which will determine the dimension of the array and convert it to char[][][][]... Actually, I will file issue `std.conv` in Phobos to add such specifications. It will suit me. Thanks to all. I just didn't know that such a conversion is running.
Re: char[][] to std::vectorstd::string - DIP or dmd-issue?
On Saturday, 13 June 2015 at 17:37:31 UTC, anonymous wrote: Please show how it is not. Seems to work just fine. OK. Still, this method works: char[][][][][][] strArr = [foo, baz], [bar, tor.to!(char[][][][][])]; But I don't want to write this `.to!(char[][][][][])`. On Saturday, 13 June 2015 at 17:37:31 UTC, anonymous wrote: Your definitions of something like that and other ways are unreasonably narrow, in my opinion. Typing out .dup is D's way to do mutable strings. You just don't like it. Yes, I don't like it.
Re: Python's features, which requires D
On Saturday, 23 May 2015 at 10:58:33 UTC, Kagamin wrote: On Saturday, 23 May 2015 at 02:36:14 UTC, Dennis Ritchie wrote: For example, the code in Python looks quite natural: a = [[int(j) for j in input().split()] for i in range(n)] About D-code, I can not say: auto a = stdin .byLine .map!(l = l.splitter.map!(to!int).array) .take(n); Well, list comprehension is built into language in python (and not in D), such level of support is definitely more streamlined. Yes, but D is also possible to create a strong inclusion of list comprehensions. Here's the proof: https://github.com/pplantinga/delight Probably the coolest feature in Delight is list comprehensions. Delight uses functions in std.algorithm to generate an iterable range. The syntax is similar to Python's. See the last two lines of the code above for an example. print { i * 2 for i in 0 .. 5 where i ^ 2 less than 5 } # prints [0, 2, 4]
Re: Reading array of integers readln performance issues
On Thursday, 11 June 2015 at 19:56:00 UTC, kerdemdemir wrote: Hi; To learn D better and challanging myself I am tring code computation's with D. There is a question which is about reading a line of integer which consist of 20 elements. My solution fails because Time limit exceeded, I thought it is because of my algorithm first. I realize time limit is exceeded even before my algorithm starts while reading line of integers. I understand this by giving a wrong answer to question after readln statement. I did that to get a wrong answer error but my code still get a Time limit exceed error because readln takes very long time. Can I achieve something faster than code below? auto peopleMoney = stdin.readln().split().map!(a = to!int(a)).array(); if (peopleMoney.length == 20) writeln(:(); Regards Erdem Ps: I do not want to bore you with long code, but I am sending link to whole program anyway if anyone need. http://codeforces.com/contest/549/submission/11537206 Your algorithm works for about quadratic time. For N = 20 your algorithm will work terribly long. The function `readln()` nothing to do with: http://codeforces.com/contest/549/submission/11476513 A faster way of `scanf`, but it will not help you, because your algorithm is slow.
Re: Json
On Thursday, 11 June 2015 at 23:58:33 UTC, Cassio Butrico wrote: What does the .json file and how to use it? In D a file with the extension *.json is used to describe packets that are included in your project, the dependency manager DUB. For example, you can install Eclipse with DDT and create a project with DUB. The file dub.json write the following: - { name : myDupApp, description : Carbon - Test., dependencies : { carbon: ~1.4.1 } } - Save the file (Ctrl + S). Then in your project with DUB downloaded package `carbon`: http://code.dlang.org/packages/carbon After that you can safely use the package `carbon`: - import std.stdio, carbon.linear;; void main() { auto m = matrix!(2, 3, (i, j) = i * 3 + j); writeln(m); // [[0, 1, 2], [3, 4, 5]] }
Re: Json
On Friday, 12 June 2015 at 00:35:35 UTC, Cassio Butrico wrote: Thank you for answering me so fast , where do I get the DUB for windows ? http://code.dlang.org/download
Re: Is it possible to add items to the arrays and hashes at compile time?
On Wednesday, 10 June 2015 at 17:43:36 UTC, Ali Çehreli wrote: On the other hand, if it's a manifest constant (enum, const static, etc.) then by definition it cannot be mutated. If we allowed mutation of compile-time expressions, then we would have a complicated language. Unfortunately, the halting problem says that the analyzer does not exist. Although I don't believe it! enum i = 42; enum j = foo(i);// Did foo() use 42 or 43? i = 43; enum k = foo(i);// Did foo() use 42 or 43? How can an enum value be changed? I find the above confusing. So in fact, if `int` is evaluated at compile time, then we won't need constants or enums. Because they almost would not make sense. Although the issues associated with immutability, complex, I think they can be solved differently. The great thing about D's CTFE is that we can use arbitrarily complex expressions as long as they are available at compile time. For example, it is possible to make 'i' above a foreach loop variable and call foo() with different values. There is nothing great. Everything is based on constexpr of C++. I want something more revolutionary :) What is your use case? I feel like it can be solved by other means. There is no precedent special :) I just want to know more about the possibilities of D and the possibility of its compiler. D made me a terrible interest in compilers :)
Re: Is it possible to add items to the arrays and hashes at compile time?
On Wednesday, 10 June 2015 at 17:13:34 UTC, anonymous wrote: On Wednesday, 10 June 2015 at 17:00:34 UTC, Dennis Ritchie wrote: Isnt it possible to come up with the interpreter compile-time, which will determine the operating time of the program at runtime at compile time. Sounds like the halting problem. So, no, generally this is not possible. Thanks. I had never heard of the halting problem. This is exactly what I wanted to know.
Re: Is it possible to add items to the arrays and hashes at compile time?
On Wednesday, 10 June 2015 at 07:15:26 UTC, Ali Çehreli wrote: My phrasing was off: By definition, initialization happens once. :) What I meant is, once initialized, a compile-time variable cannot be reassigned. The reason is, to effect compile time evaluation, one needs to use 'enum' (or 'static const') but 'enum' is a literal, i.e. it cannot be modified. As I've shown, it is possible to use an expression that will be used as the value of the compile-time variable. As long as it is evaluable at compile time, the expression can be arbitrarily complex. I understand your phrase :) I don't understand why the variables at compile time cannot be reassigned. I.e. why can't we use `int` instead of `enum` or `immutable`? Isnt it possible to come up with the interpreter compile-time, which will determine the operating time of the program at runtime at compile time. And if this time is small, it is possible to reassign variables at compile time more than once. Maybe it's something out of science fiction, but still. Is it possible somehow to create a more complex compilation process, which can reassign variables more than once?
Re: Is it possible to add items to the arrays and hashes at compile time?
On Sunday, 7 June 2015 at 15:20:17 UTC, Ali Çehreli wrote: /* Some function that generates an AA */ Thanks. Beautiful code, but I want a little more :) /* Some function that generates an AA */ int[][int][int] initHash(int i) { /* It is nice to see that this function is not called at run time */ if (!__ctfe) { import std.stdio; writefln(%s is called at run time, __FUNCTION__); } return [i : [ i : [i, i] ] ]; } /* Question: Is there a function to merge two AAs? */ int[][int][int] merge(Hash)(Hash[] hashes...) { /* It is nice to see that this function is not called at run time */ if (!__ctfe) { import std.stdio; writefln(%s is called at run time, __FUNCTION__); } int[][int][int] result; foreach (hash; hashes) { foreach (key, value; hash) { result[key] = value; } } return result; } /* These three are generated at compile time */ enum firstPart = initHash(1); enum secondPart = initHash(2); enum int[][int][int] ctHash = merge(firstPart, secondPart); void main() { import std.stdio; static if (!(4 in ctHash)) {{ // ... }} ctHash[4][4] ~= [4, 4]; // I want this to work at compile time :) // Possible? static if (!!(4 in ctHash)) {{ // ... }} }
Re: Is it possible to add items to the arrays and hashes at compile time?
On Wednesday, 10 June 2015 at 03:38:32 UTC, Ali Çehreli wrote: The way I understand it and the way it makes sense to me, :) variables that are generated at compile time can be initialized only once. It is not possible after initialization. However, the initialization of the variable can be as complex as needed: Thanks. It turns out I can do this: import std.stdio; auto merge(Hashes)(Hashes[] hashes...) { int[][int][int] result; foreach (hash; hashes) { foreach (key, value; hash) { result[key] = value; } } return result; } enum firstPart = [1 : [ 1 : [1, 1] ] ]; enum secondPart = [2 : [ 2 : [2, 2] ] ]; int[][int][int] init_ctHash(int i) { auto result = merge(firstPart, secondPart); result[i] = [ i : [i, i] ]; return result; } void main() { enum int[][int][int] ctHash = init_ctHash(5); enum t = merge(ctHash, init_ctHash(6)); writeln(t); } But I can not do so: enum int[][int][int] ctHash = init_ctHash(5); ctHash = merge(ctHash, init_ctHash(6)); I have a question: why variables may not be initialized more than once? Why can't they to resave at compile time?
Mixin - to get to the content-type `MapResult!(__lambda1, int[]).MapResult`
Hi, This code prints the arrays: [5] [6] [7] import std.stdio, std.algorithm; static int idx; void walk(R)(R range) { while (!range.empty) { range.front; range.popFront; ++idx; } } void main() { [5, 6, 7].map!(a = [a].writeln).walk; } How should I apply mixins to `range.front` to the program to print the arrays: [0, 5] [1, 6] [2, 7] Ie I want to get something like this: void walk(R)(R range) { while (!range.empty) { // mixin(`[idx ~ mixin(range.front)[1 .. $]);`); range.popFront; ++idx; } } Can I do this? - Thank you for the function `walk` Mark Isaacson of presentation DConf 2015: http://dconf.org/2015/talks/isaacson.pdf
Replacing nested loops foreach using map/each/etc
Hi, Is it possible to write such a construction that could push immediately to a conditional statement without using nested loops? Ie organize search directly in the iterator if provided by a map / each / iota and other support functions. Ie I want to write this code shorter :) import std.stdio; void main() { const x = 12, y = 65, z = 50, s = 1435; foreach (i; 0 .. x + 1) foreach (j; 0 .. x + 1) foreach (k; 0 .. x + 1) if (i * (y + 3 * z) + j * (y + 2 * z) + k * (y + z) == s) { writeln(i + j + k); writeln(i * 3 + j * 2 + k); writeln(i * 3 + j * 2 + k); writeln(i, j, k); } } - http://rextester.com/SJTU87854
Re: Replacing nested loops foreach using map/each/etc
On Monday, 25 May 2015 at 15:06:45 UTC, Alex Parrill wrote: Hint: Use `cartesianProduct` [1] with three iota ranges to replace the foreachs, and `filter` to replace the if [1] http://dlang.org/phobos/std_algorithm_setops.html#.cartesianProduct Thank you. Is it possible to replace the loop `foreach` function `each` or `chunkBy` with the auxiliary functions? import std.stdio, std.algorithm, std.range; void main() { const x = 12, y = 65, z = 50, s = 1435; auto a = iota(0, x + 1); foreach (idx; cartesianProduct(a, a, a).filter!(i = i[0] * (y + 3 * z) + i[1] * (y + 2 * z) + i[2] * (y + z) == s)) { writeln(idx[0] + idx[1] + idx[2]); writeln(idx[0] * 3 + idx[1] * 2 + idx[2]); writeln(idx[0] * 3 + idx[1] * 2 + idx[2]); writeln(idx[0], idx[1], idx[2]); } } - http://rextester.com/HZP96719
Re: Replacing nested loops foreach using map/each/etc
On Monday, 25 May 2015 at 16:41:35 UTC, Meta wrote: import std.algorithm; import std.range; import std.stdio; void main() { const x = 12, y = 65, z = 50, s = 1435; auto a = iota(0, x + 1); cartesianProduct(a, a, a) .filter!(i = i[0] * (y + 3 * z) + i[1] * (y + 2 * z) + i[2] * (y + z) == s) .each!((idx) { writeln(idx[0] + idx[1] + idx[2]); writeln(idx[0] * 3 + idx[1] * 2 + idx[2]); writeln(idx[0] * 3 + idx[1] * 2 + idx[2]); writeln(idx[0], idx[1], idx[2]); }); } Thanks. I do not even know what `each` support braces.
Re: Replacing nested loops foreach using map/each/etc
On Monday, 25 May 2015 at 19:16:04 UTC, anonymous wrote: On Monday, 25 May 2015 at 17:52:09 UTC, Dennis Ritchie wrote: But why is the solution breaks down when `s = 1` ? :) import std.stdio, std.algorithm, std.range; int c; const x = 12, y = 65, z = 50, s = 10; Which is it, now? 4 or 5 zeros? No difference! void solve(Range)(Range r) { cartesianProduct(r, r, r).filter!(i = i[0] * (y + 3 * z) + i[1] * (y + 2 * z) + i[2] * (y + z) == s).each!dout; } void main() { auto a = iota(0, x + 1).array; solve(a); writefln(`%s total`, c); } void dout(Tuple)(Tuple idx) { ++c; } - http://rextester.com/XGDL26042 What do you mean it breaks down? Your original code doesn't print anything for s = 10_000 or s = 100_000, either. Excuse me, this is my blemish! I forgot that the constant `x` depends on `s`. Everything works correctly: import std.stdio, std.algorithm, std.range; void solve(Range)(Range r) { cartesianProduct(r, r, r).filter!(i = i[0] * (y + 3 * z) + i[1] * (y + 2 * z) + i[2] * (y + z) == s).each!dout; } const y = 65, z = 50, s = 10; const x = s / (y + z); void main() { auto a = iota(0, x + 1); solve(a); } auto dout(Tuple)(Tuple idx) { writefln(`%s apples`, idx[0] + idx[1] + idx[2]); writefln(`%s gingerbread`, idx[0] * 3 + idx[1] * 2 + idx[2]); writefln(`%s pharynx tea`, idx[0] * 3 + idx[1] * 2 + idx[2]); writefln(Sour: %s; semi-acid: %s; sweet: %s.\n, idx[0], idx[1], idx[2]); } - http://rextester.com/MMCI9993
Re: Replacing nested loops foreach using map/each/etc
On Monday, 25 May 2015 at 17:19:27 UTC, Meta wrote: `each` doesn't support braces. There are 4 ways to write a function/delegate literal in D (with a few minor variations): Short form: function(int i) = i; (int i) = i (i) = i i = i Long form: function(int i) { return i; } (int i) { return i; } (i) { return i; } { return 0; } http://dlang.org/expression.html#FunctionLiteral function Thanks. But why is the solution breaks down when `s = 1` ? :) import std.stdio, std.algorithm, std.range; int c; const x = 12, y = 65, z = 50, s = 10; void solve(Range)(Range r) { cartesianProduct(r, r, r).filter!(i = i[0] * (y + 3 * z) + i[1] * (y + 2 * z) + i[2] * (y + z) == s).each!dout; } void main() { auto a = iota(0, x + 1).array; solve(a); writefln(`%s total`, c); } void dout(Tuple)(Tuple idx) { ++c; } - http://rextester.com/XGDL26042
Re: Python's features, which requires D
On Sunday, 24 May 2015 at 02:43:47 UTC, Idan Arye wrote: I'm a fan of lisp(Clojure being my favorite. Too bad it takes about a century just to load the runtime...), and yet I find it quite ironic that Paul Graham claims lisp to be the most powerful language right after claiming that programmers can't understand - and therefore disregard - the power of languages more powerful than the ones they use... This is not ironic, because I did neglect the power of Lisp, because not quite understand it fully :) The power of Lisp - his worst enemy. Strange Lisp syntax allows you to write powerful macros, which is unique in other languages, but many programmers do not understand Lisp syntax (and therefore may find it funny).
Re: Python's features, which requires D
On Sunday, 24 May 2015 at 14:15:55 UTC, Idan Arye wrote: This IS ironic, because Paul Graham claims lisp to be the most powerful, but if he have ever encounter a more powerful language he couldn't accept it is more powerful than lisp due to the very same Blub Paradox he describes himself. Probably! But, in my opinion, it has not yet appeared stronger language Lisp, so Blub Paradox is not yet threatened with Graham :)
Re: Python's features, which requires D
On Sunday, 24 May 2015 at 15:53:24 UTC, Idan Arye wrote: But according to the Blub Paradox, your(Or mine. Or Paul Graham's) opinion on whether or not a stronger language than Lisp has appeared can not be trusted! Based on an article Graham about Blub Paradox, I can conclude that Blub Paradox programmers only acts on a certain age. It is possible that this occurs after the age of 25 years. And since I am under 25 years old, I think I can be trusted completely :) - Paul Graham: This idea is rarely followed to its conclusion, though. After a certain age, programmers rarely switch languages voluntarily. Whatever language people happen to be used to, they tend to consider just good enough. ... But I don't expect to convince anyone (over 25) to go out and learn Lisp.
Re: Python's features, which requires D
On Saturday, 23 May 2015 at 21:09:45 UTC, weaselcat wrote: After another review, I think some of these conversions to D could be expressed much easier if the built-in slice had multidimensional slicing It was added in 2.066* but I don't think there's any plans to add support for it to slices. Actually not a bad idea: add to Phobos module std.multiarray. * - you can see an example at http://denis-sh.bitbucket.org/unstandard/unstd.multidimarray.html Embed multidimensional slices directly into the language is not very good, but in a separate module, why not...
Re: Python's features, which requires D
On Saturday, 23 May 2015 at 20:44:37 UTC, cym13 wrote: Not sure what kind of meat you mean, but I really don't see much meat in ranges. Of course, this is 10 times better and easier to use than STL iterators C++. For me the most important feature D are mixins, which I, unfortunately, rarely use. I'm waiting for new features from D: for new designs, not simply the expansion of Phobos and fix bugs in DMD :) Should I wait for these new features? It seems to me that everyone is not enough to simply correct C++ — they all want a language in which many different sugar. In my opinion, sugar you can try to shake out of Lisp, if possible :) I think you are mistaken. The hard part about growing a programming language isn't adding features, it's finding the right core of features that are stable yet generic enough to answer everything in their own way. This is why C still is such a popular language, it hardly evolvevd since the begginning. It is also why Java in its time or Go know are popular among companies: they are boring, just boring. But they are stable. C++ wanted to address every problem, and look at it know. We have to develop a style, not more features. Python has its own style but every new feature (and they are rare) is very diligently examined. Most are refused. There is the python way. If python isn't the right tool for the job, then the best thing to do is finding another tool, not scotch an extension to the first one. I like python. I like D. I like other languages. Of course sometimes I'd like to have, say, UFCS in python or list comprehension in D. But D isn't the best language to do python, python is. And as there is a python way, there is a D way. This is not to say that we should dismiss any good concept of other languages, but those concepts fit in a philosophy, in an ecosystem. You may find it nonsense, but Paul Graham says that each language has its own power. He believes that Lisp is the most powerful language, and programmers who write in other languages, he said Blub programmers. Learn more about The Blub Paradox can be read in the article Graham: http://www.paulgraham.com/avg.html What about increasing the number of features and stability, I agree. You may need more stability. Based on the theory of Graham, I should point out that the level of power python clearly lower than D :)
Re: Python's features, which requires D
On Saturday, 23 May 2015 at 21:32:51 UTC, anonymous wrote: On Saturday, 23 May 2015 at 21:08:19 UTC, Dennis Ritchie wrote: Perhaps that's not the site, and in Windows. That's what gives me in CMD: 456 4 4 8 99 456 [[456, 4, 4, 8, 99, 456]13 546 std.conv.ConvException@C:\D\dmd2\windows\bin\..\..\src\phobos\std\conv.d(2013): Unexpected end of input when converting from type char[] to type int That's a different issue. Works fine for me in wine. You may be typing spaces before/after the numbers. Yes, I think I scored one space after 546.
Re: Python's features, which requires D
On Saturday, 23 May 2015 at 19:22:40 UTC, Alex Parrill wrote: import std.algorithm; import std.range; import std.stdio; import std.conv; void main() { enum n1 = 5; writeln(stdin.byLine .map!(line = line.split( ).map!(x = to!int(x))) ); writeln(--); enum n2 = 6; writeln(iota(n2) .map!(i = chain( repeat(2, i), only(1), repeat(0, n2 - i - 1), only(\n) ).joiner( )).joiner ); } (I omitted evens/odds because it's been addressed and fizzbuzz because there's probably dozens of them floating around) You seem to be focusing on D's arrays only, but the real meat is in ranges, which are more generic. Also note that the above solution doesn't allocate any of the ranges in the heap; they're all on the stack (as opposed to Python, where you have to allocate lists or use iterators+itertools). This does not work! enum n1 = 5; writeln(stdin.byLine .map!(line = line.split( ).map!(x = to!int(x))) ); - http://rextester.com/VGHZF81178 Even if you wanted to write this: enum n = 5; writeln(stdin.byLine .map!(line = line.split( ).map!(x = to!int(x))).take(n) ); - http://rextester.com/COWE75794 That it's still not working. In my opinion, and should not work :) You seem to be focusing on D's arrays only, but the real meat is in ranges, which are more generic. Not sure what kind of meat you mean, but I really don't see much meat in ranges. Of course, this is 10 times better and easier to use than STL iterators C++. For me the most important feature D are mixins, which I, unfortunately, rarely use. I'm waiting for new features from D: for new designs, not simply the expansion of Phobos and fix bugs in DMD :) Should I wait for these new features? It seems to me that everyone is not enough to simply correct C++ — they all want a language in which many different sugar. In my opinion, sugar you can try to shake out of Lisp, if possible :) Also note that the above solution doesn't allocate any of the ranges in the heap; they're all on the stack (as opposed to Python, where you have to allocate lists or use iterators+itertools). And yet I do not like how the function byLine. It seems to me that we need analogues that will not work so damp as byLine. All right. Next time I will try to combine features that are not available in D, and of the faster languages: Erlang, Perl, Lisp, Nim, Rust, Scala etc. :)
Re: Python's features, which requires D
On Saturday, 23 May 2015 at 19:22:40 UTC, Alex Parrill wrote: You seem to be focusing on D's arrays only, but the real meat is in ranges, which are more generic. Also note that the above solution doesn't allocate any of the ranges in the heap; they're all on the stack (as opposed to Python, where you have to allocate lists or use iterators+itertools). Also present ranges from the time of D1 and Tango, because there is nothing surprising about them. Need new features!
Re: Python's features, which requires D
On Saturday, 23 May 2015 at 20:57:10 UTC, anonymous wrote: On Saturday, 23 May 2015 at 20:25:18 UTC, Dennis Ritchie wrote: This does not work! enum n1 = 5; writeln(stdin.byLine .map!(line = line.split( ).map!(x = to!int(x))) ); - http://rextester.com/VGHZF81178 The code itself is ok. That site has broken newlines. You can see here that std.ascii.newline is different from what the site actually feeds to the program: http://rextester.com/IIT33098. You can work around that by passing the correct line terminator to byLine: http://rextester.com/SOW95508. Perhaps that's not the site, and in Windows. That's what gives me in CMD: 456 4 4 8 99 456 [[456, 4, 4, 8, 99, 456]13 546 std.conv.ConvException@C:\D\dmd2\windows\bin\..\..\src\phobos\std\conv.d(2013): Unexpected end of input when converting from type char[] to type int 0x0040FD10 in pure @safe int std.conv.parse!(int, char[]).parse(ref char[]) at C:\D\dmd2\windows\bin\..\..\src\phobos\std\conv.d(2015) 0x00410C74 in pure @safe int std.conv.toImpl!(int, char[]).toImpl(char[]) at C:\D\dmd2\windows\bin\..\..\src\phobos\std\conv.d(1738) 0x0040FB92 in pure @safe int std.conv.to!(int).to!(char[]).to(char[]) at C:\D\dmd2\windows\bin\..\..\src\phobos\std\conv.d(296) 0x0040FB7E in pure @safe int acm.main().__lambda1!(char[]).__lambda1(char[]).__lambda2!(char[]).__lambda2(char[]) 0x00410DA7 in pure @property @safe int std.algorithm.iteration.__T9MapResultS553acm4mainFZ17__T9__lambda1TAaZ9__lambda1MFAaZ9__lambda2TAAaZ.MapResult.front() at C:\D\dmd2\windows\bin\..\..\src\phobos\ std\algorithm\iteration.d(548) 0x004122D4 in D3std6format169__T11formatRangeTS3std5stdio4File17LockingTextWriterTS3std9algorithm9iteration76A5C81813C007BD25AC82BE82F3551A66 at C:\D\dmd2\windows\bin\..\..\src\phobos\std\format.d(240 9) 0x0041213F in D3std6format169__T11formatValueTS3std5stdio4File17LockingTextWriterTS3std9algorithm9iteration768E862681E57D43E301EA954AAC63F894 at C:\D\dmd2\windows\bin\..\..\src\phobos\std\format.d(311 2) 0x004120AA in D3std6format171__T13formatElementTS3std5stdio4File17LockingTextWriterTS3std9algorithm9iterationC8BE2524D6E8B27505208FE77A7AABE7 at C:\D\dmd2\windows\bin\..\..\src\phobos\std\format.d(261 9) 0x00411B89 in D3std6format172__T11formatRangeTS3std5stdio4File17LockingTextWriterTS3std9algorithm9iteration7956A969C910F877511562257DEEBA50CE at C:\D\dmd2\windows\bin\..\..\src\phobos\std\format.d(241 0) 0x00411A27 in D3std6format172__T11formatValueTS3std5stdio4File17LockingTextWriterTS3std9algorithm9iteration793B5F1700DB9877FAF5528C7A1A67E5DC at C:\D\dmd2\windows\bin\..\..\src\phobos\std\format.d(311 2) 0x00411991 in D3std6format174__T13formatGenericTS3std5stdio4File17LockingTextWriterTS3std9algorithm9iterationD44607637B1FEE3931BFD9A68911D4FE at C:\D\dmd2\windows\bin\..\..\src\phobos\std\format.d(345 1) 0x0041185C in D3std6format175__T14formattedWriteTS3std5stdio4File17LockingTextWriterTaTS3std9algorithm9iteratD57474F5CD8E0DF85B780AE37888E8BE at C:\D\dmd2\windows\bin\..\..\src\phobos\std\format.d(521 ) 0x00411320 in D3std5stdio4File129__T5writeTS3std9algorithm9iteration79__T9MapResultS213acm4mainFZ9__lambda1TSD37A9C7F430415C668F40B8F70856955 at C:\D\dmd2\windows\bin\..\..\src\phobos\std\stdio.d(1200 ) 0x0041120A in D3std5stdio129__T7writelnTS3std9algorithm9iteration79__T9MapResultS213acm4mainFZ9__lambda1TS3stC41BC71D1E9C2BC78EB8446AC4667CCD at C:\D\dmd2\windows\bin\..\..\src\phobos\std\stdio.d(2932 ) 0x0040203D in _Dmain at C:\Users\REiS\Documents\Projects\acm\acm\acm.d(21) 0x00427E06 in D2rt6dmain211_d_run_mainUiPPaPUAAaZiZ6runAllMFZ9__lambda1MFZv 0x00427DDB in void rt.dmain2._d_run_main(int, char**, extern (C) int function(char[][])*).runAll() 0x00427CF3 in _d_run_main 0x00427884 in main 0x0043E701 in mainCRTStartup 0x76BB7C04 in BaseThreadInitThunk 0x775AAD1F in RtlInitializeExceptionChain 0x775AACEA in RtlInitializeExceptionChain
Re: Python's features, which requires D
On Saturday, 23 May 2015 at 10:58:33 UTC, Kagamin wrote: Well, list comprehension is built into language in python (and not in D), such level of support is definitely more streamlined. Well, what's to keep D more functions to work with slist and dlist ? In my opinion, lists in D completely bald :) After all, there is a module in Phobos std.array, so why not make the module std.list. Do lists in D can be done as powerful as arrays?
Re: Python's features, which requires D
On Friday, 22 May 2015 at 05:31:38 UTC, Ali Çehreli wrote: Here is my attempt: import std.stdio; import std.algorithm; import std.conv; import std.range; void main() { // Replace 'none' with 'all' to activate. version (none) { const n = 5; auto a = stdin .byLine .map!(l = l.splitter.map!(to!int).array) .take(n); writeln(a); writeln(-); } { const n = 6; auto a = iota(n) .map!(i = chain([2].replicate(i), [1], [0].replicate(n - i - 1))); writefln(%(%(%s %)\n%), a); writeln(-); } { const x = [ 1, 2, 3, 4, 5, 6 ]; writeln(x.stride(2)); writeln(x.dropOne.stride(2)); writeln(-); } { // The internet does not need another fizz buzz. :p } } Ali Yes, it looks pretty good :) Thanks. But... It seems to me that D lacks features that allow you to write function readln/readln.strip/readln.split just inside the lambda. stdin.byLine is a good feature, but it captures the entire input stream, which I should handle all or take lambdas function take(n) n lines and then still handle all of these lines right away. Ie stdin.byline used everywhere is not always convenient! For example, the code in Python looks quite natural: a = [[int(j) for j in input().split()] for i in range(n)] About D-code, I can not say: auto a = stdin .byLine .map!(l = l.splitter.map!(to!int).array) .take(n); I can call the map with the existing array: import std.stdio, std.algorithm, std.conv, std.array; void main() { auto a = [1, 2, 3]; auto b = a.map!(c = c ~ readln.split.map!(to!int).array).array; writeln(b); } - http://rextester.com/MBUMHI13858 But I can not call the readln n times without a map: import std.stdio, std.conv, std.algorithm, std.array, std.range; void main() { auto a = [1, 2, 3]; auto b = [readln.split.map!(to!int).array].take(3); writeln(b); } - http://rextester.com/KCJ9346 Ie readln function cycle is needed for, another lambda or revised map! Is there a function in Phobos?
Re: Python's features, which requires D
By the way, Python has deepDup :) http://rextester.com/KBFA82886
Re: Dual conditions in D and Python
On Thursday, 21 May 2015 at 17:43:25 UTC, Jonathan M Davis wrote: No C-based language allows what python does, and based on operators work in C-based languages, what python is doing simply doesn't fit or make sense. What happens in C/C++/D/Java/C#/etc. land is that 4 = 5 results in a bool, at which point you'd end up with a comparison between that bool and 6, which is _not_ something that you want. But with other operators _is_ very much what you'd want. Operator chaining works in the same way across all operators in C-based languages, and trying to make 4 = 5 = 6 be equivalent to 4 = 5 5 = 6 would make it so that they weren't consistent. And it wouldn't make the language any more powerful, because you can quite easily just do 4 = 5 5 = 6 instead of 4 = 5 = 6. It only costs you a few characters and results in the language being far more consistent. I'm honestly quite surprised that python would allow such a thing, but they seem to do a lot of stuff that most programmers from C-based languages (especially C++) would think is crazy. - Jonathan M Davis Yes, of course, some of Python's design for C ++ - programmers will look crazy, but they are worth it :) elif instead of else if: http://rextester.com/WOSH30608 The parallel exchange values: http://rextester.com/TPUD51604
Re: Dual conditions in D and Python
On Thursday, 21 May 2015 at 21:35:22 UTC, Ali Çehreli wrote: We're almost there. :) bool is_between(T0, T1, T2)(T0 what, T1 min, T2 max) { return (what = min) (what = max); } void main() { if (5.is_between(4, 6)) { // ... } } Ali A condition is that if, for example, that? :) if (5 2 -9 -13 10 == 10 21 != 45): print(OK) - http://rextester.com/JSC75231 import std.stdio; void main() { if (5 2 2 -9 -9 -13 -13 10 10 == 10 10 21 21 != 45) writeln(OK); } - http://rextester.com/AZFL70044
Re: Python's features, which requires D
On Friday, 22 May 2015 at 01:17:17 UTC, weaselcat wrote: D doesn't have list comprehensions, so it's difficult to directly port these. I can not imagine how difficult it is to implement it in D, but I'm pretty sure that nested for loops to fill arrays (in D, you can call them differently, for example, force :)) will be very useful thing, because Python is a veryIt is often used. Besides, I do not understand what could be the problem with nested loops in arrays, because std.algorithm.map works on the principle of nested loops. I think that the biggest problem in the implementation of this should not be. Excuse me if I'm wrong. off the top of my head, the last one can easily be done with std.range.stride import std.stdio, std.range; void main() { int[] a = [ 1, 2, 3, 4, 5, 6 ]; writeln(stride(a, 2)); // [1, 3, 5] #odd #print(x[::2]) #OK // [2, 4, 6] #even #print(x[1::2]) #no equivalent in D auto x = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; // [2, 6, 10] #print(x[1::4]) #no equivalent in D }
Re: Python's features, which requires D
On Friday, 22 May 2015 at 02:18:23 UTC, weaselcat wrote: On Friday, 22 May 2015 at 01:52:30 UTC, Dennis Ritchie wrote: off the top of my head, the last one can easily be done with std.range.stride import std.stdio, std.range; void main() { int[] a = [ 1, 2, 3, 4, 5, 6 ]; writeln(stride(a, 2)); // [1, 3, 5] #odd #print(x[::2]) #OK // [2, 4, 6] #even #print(x[1::2]) #no equivalent in D writeln(stride(a[1..$], 2)); auto x = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; // [2, 6, 10] #print(x[1::4]) #no equivalent in D writeln(stride(a[1..$], 4)); } Yes, this is what you need (I often forget that the functions can take ranges in D). Maybe somewhere and nested loops for to fill the arrays lying around :)
Python's features, which requires D
Hi, I've collected some of Python's features. It seems to me that they are not in the D! Surely all this is in the D? :) http://rextester.com/CNQQR
Re: Dual conditions in D and Python
Something I sometimes do for strictly personal projects: import std.typecons : ω = tuple; import std.typetuple : Ω = TypeTuple; void main() { auto a = 1, b = 2; Ω!(a, b) = ω(b, a); assert(a==2 b==1); } On Thursday, 21 May 2015 at 19:05:16 UTC, Steven Schveighoffer wrote: On 5/21/15 12:57 PM, Dennis Ritchie wrote: Hi, In Python I can write this: if (4 = 5 = 6): print (OK) - http://rextester.com/NNAM70713 In D, I can only write this: import std.stdio; void main() { if (4 = 5 5 = 6) puts(OK); } - http://rextester.com/FICP83173 I wanted to ask what is the reason? Maybe the program on Python's slower because of this? Or legacy C/C++ affected D? There is this possibility: switch(5){ case 4: .. case 6: } You could also make some nifty abuse-of-syntax types: struct Between(T) { T low; T high; bool opBinaryRight!(op : in)(T val) { return val = low val = high;} } auto between(T)(T low, T high) { return Between!T(low, high); } if(5 in between(4, 6)) :) -Steve All this, of course, looks good, but what about the principle of the ideal programming language :) In the end I want to focus on one philosophical principle, which lies at the basis of my ideas about the ideal programming language. Typically, during the discussion in the forums, when you start to talk in a language that is not X features Y, be sure there is someone who will say: Why, that's if you take the features A, B and C, and screw them crutches D, E, F, then we will get almost Y. Yes, it is. But I do not like this approach. One can imagine that such programmers want some complicated way through the maze. You can go through the maze, but the way the curve and non-obvious. I also want to be instead of the labyrinth has a large area, on which from any point to any other one would go in a straight line. Just a straight line. - The quotation is taken from the article: http://habrahabr.ru/post/257875/
Dual conditions in D and Python
Hi, In Python I can write this: if (4 = 5 = 6): print (OK) - http://rextester.com/NNAM70713 In D, I can only write this: import std.stdio; void main() { if (4 = 5 5 = 6) puts(OK); } - http://rextester.com/FICP83173 I wanted to ask what is the reason? Maybe the program on Python's slower because of this? Or legacy C/C++ affected D?
Re: Dual conditions in D and Python
On Thursday, 21 May 2015 at 17:17:29 UTC, Alex Parrill wrote: http://wiki.dlang.org/Language_Designs_Explained#Why_does_D_not_support_chaining_comparison_operators.3F Backward compatibility with C is nice but on the other hand it is a road to nowhere! Because of this compatibility, I'm compelled to write return instead of ret and else if instead of elif :) I think to create a truly correct C++, it was necessary to completely abandon the backward compatibility with C.
Re: How to create a mutable array of strings?
On Monday, 18 May 2015 at 13:14:38 UTC, Steven Schveighoffer wrote: It's annoying to have to dup each one. Yes, it's really annoying. However, the problem can be solved as follows: http://forum.dlang.org/thread/owxweucyzjwugpjwh...@forum.dlang.org?page=2#post-cqjevoldkqdkmdbenkul:40forum.dlang.org On Monday, 18 May 2015 at 13:14:38 UTC, Steven Schveighoffer wrote: But, you do have a couple other possibilities: auto s = [foo.dup, bar.dup]; import std.algorithm : map; import std.array : array; auto s = map!(a = a.dup)([foo, bar]).array; // this will needlessly allocate an array for the strings Now imagine that you have a multi-dimensional array of strings. This will not work: auto s = map!(a = a.dup)([[foo, baz], [bar, test]]).array; You have to apply to each line .dup :) auto s = [[foo.dup, baz.dup], [bar.dup, test.dup]]; s[1][0][1] = 't'; On Monday, 18 May 2015 at 13:14:38 UTC, Steven Schveighoffer wrote: But really, a string is immutable. There's not a way around that. A string is the most basic level of array primitive, not even mutable arrays of non-char types have that, and it's an annoyance. From there, you have to build the data out of ROM into the heap. Thank you. I do not know. And yet, the problem is easily solved. You just have to add .deepDup Phobos: http://forum.dlang.org/thread/owxweucyzjwugpjwh...@forum.dlang.org?page=2#post-cqjevoldkqdkmdbenkul:40forum.dlang.org
The analogue of fill-pointer in D
Hi, In Common Lisp, there is such a thing as a fill-pointer (Example 5): http://www.tutorialspoint.com/lisp/lisp_arrays.htm Does D some equivalent?
Re: The analogue of fill-pointer in D
On Monday, 18 May 2015 at 10:14:33 UTC, Kagamin wrote: On Monday, 18 May 2015 at 08:21:38 UTC, Dennis Ritchie wrote: Hi, In Common Lisp, there is such a thing as a fill-pointer (Example 5): http://www.tutorialspoint.com/lisp/lisp_arrays.htm Does D some equivalent? Data stored in the array is indicated by the array length property, use capacity to figure out extra available space: http://dlang.org/phobos/object.html#.capacity No, afraid not. Function capacity is not an analogue of fill-pointers! Lisp-programmer explains the usefulness of fill-pointers as follows: Fill pointer cuts the tail of the vector. For example, vector elements 100, but if you set the fill pointer equal to 3, the length of the array (returned by length) will be equal to 3. The remaining elements are not visible. It seems to be nonsense. But this is nonsense, ideal for buffers. If the buffer is implemented as an array, then fill pointer just marks the boundary of the filled part of the buffer, and adding a buffer (moving away from the fill pointer-a) is carried out using the vector-push. Or a buffer can be filled with the format-a. If you work with the same buffer C, fill pointer simulates a pointer to the last completed item.
Re: How to create a mutable array of strings?
On Monday, 18 May 2015 at 14:43:33 UTC, Steven Schveighoffer wrote: Right, you'd apply the map/array combo to each element: Yes, I knew it. alias m = map!(a = a.dup); // too bad can't do array as well auto s = [m([foo, baz]).array, m([bar, test]).array]; Or to get even more crazy: auto s = map!(a = map!(a = a.dup)(a).array)(/* your input array */).array; Imagine a five-dimensional array will be :) But this means you are duping more of the array literal than you really should. It's likely helpful to have somewhere in std.array a dupArray function that does map!(a = a.dup).array work in one go (and without making a temporary array): auto s = [dupArray(foo, baz), dupArray(bar, test)]; Yes, it would be nice. I believe that Phobos need such function. deepDup would dup the whole thing. All you need to dup is the string literals, as array literals constructed at runtime are on the heap (and mutable) already. The literal already is wasted even in my original suggestion, but this is doubly wasteful. Right.
Re: The analogue of fill-pointer in D
On Monday, 18 May 2015 at 12:49:56 UTC, Kagamin wrote: Filling a buffer is usually done this way: http://dlang.org/phobos/std_stdio.html#.File.rawRead Here such example, the task. There is a flow stream, associated, for example, with any socket. It wrote several bytes at a time. To once again not to pull the socket, we start buffer as an array with Phill-pointer. Adding byte array - using the vector-push. When the buffer is stuffed, dump it into the stream and moves pointer to zero. How to do it with the help of readRaw or there writeRaw?
Re: The analogue of fill-pointer in D
On Monday, 18 May 2015 at 17:14:46 UTC, Steven Schveighoffer wrote: capacity is analogous to the number of elements in the vector (as returned by array-dimension according to https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node162.html). arr.length is analogous to the fill pointer. example: int[] arr = new int[](5); assert(arr.capacity 5); assert(arr.length == 5); arr.reserve(100); // expand arr memory block to be able to hold *at least* 100 ints assert(arr.capacity = 100); assert(arr.length == 5); auto ptr = arr.ptr; // for later assert arr ~= 1; // increment length by 1, 'fill in' tail of array with '1' // this should demonstrate how it works assert(arr.length == 6); // new fill pointer assert(arr.capacity = 100); // capacity unchanged assert(arr.ptr is ptr); // array still lives in same memory block Apologies for not translating to lisp, I don't know it. -Steve Thank you. This is what you need!
Re: How to create a mutable array of strings?
On Sunday, 17 May 2015 at 09:06:40 UTC, Dennis Ritchie wrote: Hi, It seems to me, or D do not create mutable array of strings? How to create a mutable equivalent of a string array? - string[] s = [foo, bar]; // s[1][1] = 't'; // immutable expression s[1][1] It's uncomfortable: - char[][] s = [['f', 'o', 'o'], ['b', 'a', 'r']]; s[1][1] = 't';
How to create a mutable array of strings?
Hi, It seems to me, or D do not create mutable array of strings? How to create a mutable equivalent of a string array? - string[] s = [foo, bar]; // s[1][1] = 't'; // immutable expression s[1][1]
Re: How to create a mutable array of strings?
This option is also a strange: char[][] s = [foo.dup, bar.dup]; s[1][1] = 't'; In my opinion, you need to add to D keyword mutable.
Re: How to create a mutable array of strings?
On Sunday, 17 May 2015 at 09:18:15 UTC, Daniel Kozak wrote: auto s = cast(char[][])[foo, bar]; Thanks. This version I was completely satisfied.
Re: How to create a mutable array of strings?
On Sunday, 17 May 2015 at 09:24:19 UTC, anonymous wrote: On Sunday, 17 May 2015 at 09:20:17 UTC, Dennis Ritchie wrote: On Sunday, 17 May 2015 at 09:18:15 UTC, Daniel Kozak wrote: auto s = cast(char[][])[foo, bar]; Thanks. This version I was completely satisfied. Remember that Daniel Kozak wrote if you are sure thats what you really need. I'm confident that you're not sure it's what you need. For starters, this crashes on linux: auto s = cast(char[][])[foo, bar]; s[1][1] = 't'; And no crashes on Windows :)
Re: How to create a mutable array of strings?
I remembered code Ali Çereli. It really helped: http://forum.dlang.org/thread/ulhtlyxxclihaseef...@forum.dlang.org#post-mihl6m:241che:241:40digitalmars.com - import std.stdio, std.traits, std.range, std.algorithm; auto deepDup(A)(A arr) if (isArray!A) { static if (isArray!(ElementType!A)) { return arr.map!(a = a.deepDup).array; } else { return arr.dup; } } void main() { auto s = [foo, bar].deepDup; s[1][1] = 't'; writeln(s); } - http://rextester.com/QBFH12695 P.S. Need to enable deepDup in Phobos.
Re: How to create a mutable array of strings?
On Sunday, 17 May 2015 at 09:36:33 UTC, anonymous wrote: On Sunday, 17 May 2015 at 09:26:15 UTC, Dennis Ritchie wrote: And no crashes on Windows :) Yeah, on windows it's even worse. void main() { auto s = cast(char[][])[foo, bar]; s[1][1] = 't'; import std.stdio; writeln(bar); } Yes exactly.
Re: How to create a mutable array of strings?
On Sunday, 17 May 2015 at 09:37:56 UTC, Daniel Kozak wrote: So maybe this one would be ok with you too :) auto s = to!(char[][])([foo, bar]); Now it works :)
Re: How to create a mutable array of strings?
On Sunday, 17 May 2015 at 10:05:34 UTC, Daniel Kozak wrote: Ouch ignore this one :D Yes, it will not work with multidimensional arrays :)
Re: Feature or bug: print braces
On Friday, 15 May 2015 at 08:44:41 UTC, Ivan Kazmenko wrote: Somehow reminds me of this lambda: https://github.com/Hackerpilot/Idiotmatic-D/blob/master/idiotmatic.d#L127-L128 Maybe it generally blocks for initialization of variables: https://github.com/Hackerpilot/Idiotmatic-D/blob/master/idiotmatic.d#L130-L131 - for ( { int i = 0; } i 5; ++i ) { writeln(test); } It seems to me that this should be fixed :) - int x; void foo(int tmp) { x = tmp; } ... writeln( { int i = 5; writeln(i); foo(i); }); writeln(x);
Re: Feature or bug: print braces
On Thursday, 14 May 2015 at 21:55:40 UTC, Alex Parrill wrote: On Thursday, 14 May 2015 at 00:39:25 UTC, Dennis Ritchie wrote: On Thursday, 14 May 2015 at 00:33:33 UTC, Brian Schott wrote: You told it to output a function literal, so it did. Yes, but it would be logical to deduce something like: - writeln({}); // prints literal[{}] Or the compiler will not be able to distinguish the literal from the ordinary function arguments? Literal what? Associative array? That uses square brackets, not curly brackets. Struct? What struct would you be creating? And curly braces only works for initialization. Lambda? Well you can omit the parameters if there are none, and `{}` in a lambda will give you a block to write, so `{}` is a valid lambda that accepts nothing and does nothing. I just wanted to say that writeln function of demand should not print anything else at this challenge, not 804CF88 :) - writeln({});
Re: Feature or bug: print braces
On Thursday, 14 May 2015 at 22:55:43 UTC, Ali Çehreli wrote: Yes, it is weird but that value happens to be the address of the function. Here is another test: import std.stdio; void foo() pure nothrow @nogc @safe {} void main() { void printInfo(T)(T t) { writefln(%s %s, T.stringof, t); } auto f = (){};// -- Why the need for () here? printInfo(foo); printInfo(f); printInfo({});// -- No need for () here. } There is an inconsistency where a lambda need to be defined with empty parentheses in one context while it is just fine without in another context. One output shows that they are all of the same type (function pointers): void function() pure nothrow @nogc @safe 473264 void function() pure nothrow @nogc @safe 4732BC void function() pure nothrow @nogc @safe 4732C4 Ali Thanks. This example explains a lot. It's like echoes UFCS :)
Re: Feature or bug: print braces
Turns out that I can put into the function writeln almost any design language: - import std.stdio; void main() { writeln( { int n = 5; } ); } - http://ideone.com/Rp7gZ2
Re: Feature or bug: print braces
On Thursday, 14 May 2015 at 00:33:33 UTC, Brian Schott wrote: You told it to output a function literal, so it did. Yes, but it would be logical to deduce something like: - writeln({}); // prints literal[{}] Or the compiler will not be able to distinguish the literal from the ordinary function arguments?
Feature or bug: print braces
Why doesn't the compiler produces an error? - import std.stdio; void main() { writeln({}); } - http://ideone.com/qTZCAd
Re: Lambda functions in D
On Saturday, 9 May 2015 at 21:48:05 UTC, Timon Gehr wrote: Well, it is much slower due to all the allocated closures, owed to the fact that the implementations of 'fix' on that page are expected to mirror a particular famous implementation in untyped lambda calculus. In case you have a use for 'fix', a more efficient implementation might be: auto fix(S,T...)(S delegate(T) delegate (S delegate(T)) f){ S delegate(T) g=(T a){ assert(0,f is too eager.); }; return g=f((T a)=g(a)); } (In particular, this will only allocate two closures for the plumbing instead of a number of them linear in the number of recursive invocations.) Even something like Common Lisp. (Be aware that Common Lisp implementations typically have better garbage collectors than what is available for D.) Maybe in the future, that D will be added to optimize tail recursion delegates? And why garbage collectors in Lisp is better?
Lambda functions in D
Hi, Can lambda functions or delegates in D to call themselves? Can I write something like this: - import std.stdio; void main() { auto fact = function (int x) = x * { if (x) fact(x - 1); }; assert(fact(10) == 3628800); }
Re: Lambda functions in D
On Saturday, 9 May 2015 at 11:49:48 UTC, Timon Gehr wrote: assert((function int(int x)=x?x*__traits(parent,{})(x-1):1)(10)==3628800); Thanks. Yes, it is similar to what I wanted :)
Re: Lambda functions in D
On Saturday, 9 May 2015 at 14:15:21 UTC, Ali Çehreli wrote: On 05/09/2015 04:59 AM, Dennis Ritchie wrote: On Saturday, 9 May 2015 at 11:49:48 UTC, Timon Gehr wrote: assert((function int(int x)=x?x*__traits(parent,{})(x-1):1)(10)==3628800); Thanks. Yes, it is similar to what I wanted :) Also interesting: http://rosettacode.org/wiki/Y_combinator#D I think that code was improved by Timon Gehr as well. Ali Yes, it's much better. Even something like Common Lisp.
Re: Why .dup not work with multidimensional arrays?
On Friday, 8 May 2015 at 06:30:46 UTC, Ali Çehreli wrote: In D, everything is possible and very easy. :p I called it deepDup: import std.stdio; import std.traits; import std.range; import std.algorithm; auto deepDup(A)(A arr) if (isArray!A) { static if (isArray!(ElementType!A)) { return arr.map!(a = a.deepDup).array; } else { return arr.dup; } } void main() { auto c = [[[1, 2, 3], [4, 5, 6, 7, 8]], [[9, 10], [11, 12, 13]]]; auto d = c.deepDup; d[0][1][1 .. $ - 1] *= 3; writeln(c = , c); // [[[1, 2, 3], [4, 5, 6, 7, 8]], // [[9, 10], [11, 12, 13]]] // OK writeln(d = , d); // [[[1, 2, 3], [4, 15, 18, 21, 8]], // [[9, 10], [11, 12, 13]]] // OK } Ali Thank you. In D it's really easy :) Recursion, which works with the lambda map looks fine. I was a little question: why static int idx variable declared within a function deepDup takes the values 1, 1, 1, 2, 2, 3, 4, as opposed to a global variable static int idx, which receives the expected value of 1, 2, 3, 4, 5, 6, 7 ? - import std.stdio, std.range, std.traits, std.algorithm; // static int idx; // 1, 2, 3, 4, 5, 6, 7 // OK auto deepDup(A)(A arr) if (isArray!A) { static int idx; // 1, 1, 1, 2, 2, 3, 4 // Why is this happening? ++idx; writeln(visited); static if (isArray!(ElementType!A)) { writeln(ifIdx = , idx); writeln(ifArr = , arr); return arr.map!(a = a.deepDup).array; } else { writeln(elseIdx = , idx); writeln(elseArr = , arr); return arr.dup; } } void main() { auto a = [[[1, 2, 3], [4, 5, 6, 7, 8]], [[9, 10], [11, 12, 13]]]; auto b = a.deepDup; b[0][1][1 .. $ - 1] *= 3; writeln(\nResualt: ); writeln(a = , a); // [[[1, 2, 3], [4, 5, 6, 7, 8]], // [[9, 10], [11, 12, 13]]] writeln(b = , b); // [[[1, 2, 3], [4, 15, 18, 21, 8]], // [[9, 10], [11, 12, 13]]] } - http://ideone.com/mAHZyO
Re: Why .dup not work with multidimensional arrays?
On Friday, 8 May 2015 at 15:13:14 UTC, Ali Çehreli wrote: On 05/08/2015 08:05 AM, Dennis Ritchie wrote: why static int idx variable declared within a function deepDup takes the values 1, 1, 1, 2, 2, 3, 4, as opposed to a global variable static int idx, which receives the expected value of 1, 2, 3, 4, 5, 6, 7 ? That's because every template instance is a different type (or implementation). Just like the static variables of foo and bar are separate below, so are the static variables of t!int and t!float: void foo() { static int i; } void bar() { static int i; } void t(T)() { static int i; } Ali Thankы. Now everything is clear.
Re: Baffled by compilation error for formattedRead
On Thursday, 7 May 2015 at 23:13:41 UTC, PhilipDaniels wrote: On Thursday, 7 May 2015 at 23:10:26 UTC, PhilipDaniels wrote: Let's try reformatting that... ubyte r, g, b; // does not compile auto numRead = formattedRead(dropExactly(input, 4), %x/%x/%x, r, g, b); // does not compile auto numRead = formattedRead(input[4..$], %x/%x/%x, r, g, b); // compiles string s2 = input[4..$]; auto numRead = formattedRead(s2, %x/%x/%x, r, g, b); Alternatively, I can suggest to use the function csvReader(): - import std.csv, std.stdio, std.format; void main() { auto input = rgb:10/30/40; input = input[4 .. $]; ubyte r, g, b; formattedRead(input, %s/%s/%s, r, g, b); auto numRead = [r, g, b]; string[] numReadHex; foreach (e; numRead) { numReadHex ~= format(%x, e); } writeln(numRead); // [10, 30, 40] writeln(numReadHex);// [a, 1e, 28] auto inputNew = rgb:10/30/40; auto newNumRead = csvReader!int(inputNew[4 .. $], '/').front; writeln(newNumRead); // [10, 30, 40] }
Why .dup not work with multidimensional arrays?
Hi, Should the method .dup work with multidimensional arrays for copying? - import std.stdio; void main() { auto a = [1, 2, 3]; auto b = a.dup; b[] *= 2; writeln(a = , a); // [1, 2, 3] // OK writeln(b = , b); // [2, 4, 6] // OK auto c = [[[1, 2, 3], [4, 5, 6, 7, 8]], [[9, 10], [11, 12, 13]]]; auto d = c.dup; writeln(d[0][1][1 .. $ - 1] = , d[0][1][1 .. $ - 1]); d[0][1][1 .. $ - 1] *= 3; writeln(c = , c); // [[[1, 2, 3], [4, 15, 18, 21, 8]], // [[9, 10], [11, 12, 13]]] // wrong writeln(d = , d); // [[[1, 2, 3], [4, 15, 18, 21, 8]], // [[9, 10], [11, 12, 13]]] // OK } - http://ideone.com/Ddtm47 I thought the slice of the array c[0][1][1 .. $ - 1] = [5, 6, 7] not had to change to [15, 18, 21] by multiplying by 3.
Re: Why .dup not work with multidimensional arrays?
On Friday, 8 May 2015 at 02:23:23 UTC, E.S. Quinn wrote: It's because arrays are references types, and .dup is a strictly shallow copy, so you're getting two outer arrays that reference the same set of inner arrays. You'll have to duplicated each of the inner arrays yourself if you need to make a deep copy. Thank you. It really works :) - import std.stdio; void main() { auto c = [[[1, 2, 3], [4, 5, 6, 7, 8]], [[9, 10], [11, 12, 13]]]; auto d = [[c[0][0].dup, c[0][1].dup], [c[1][0].dup, c[1][1].dup]]; d[0][1][1 .. $ - 1] *= 3; writeln(c = , c); // [[[1, 2, 3], [4, 5, 6, 7, 8]], // [[9, 10], [11, 12, 13]]] // OK writeln(d = , d); // [[[1, 2, 3], [4, 15, 18, 21, 8]], // [[9, 10], [11, 12, 13]]] // OK } - http://ideone.com/kJVUhd Maybe there is a way to create .globalDup for multidimensional arrays?
Re: Ada to D - an array for storing values of each of the six bits which are sufficient
Realized bitmap, sorry that does not work with DMD 2.067.1: http://vlang.org/docs/Data_Types/Bits_and_Logic.html https://github.com/coverify/vlang/blob/master/src/esdl/data/bvec.d
Re: std.random question
On Sunday, 3 May 2015 at 09:04:07 UTC, tired_eyes wrote: On Sunday, 3 May 2015 at 08:48:52 UTC, Dennis Ritchie wrote: On Sunday, 3 May 2015 at 08:42:57 UTC, tired_eyes wrote: Feels pretty silly, but I can't compile this: import std.random; auto i = uniform(0, 10); DMD spits this: /usr/include/dmd/phobos/std/random.d(1188): Error: static variable initialized cannot be read at compile time /usr/include/dmd/phobos/std/random.d(1231):called from here: rndGen() /usr/include/dmd/phobos/std/random.d(1231):called from here: uniform(a, b, rndGen()) Perhaps I'm missing something obvious? dmd 2.067.1, openSUSE 13.2 x64 void main() { import std.random; auto i = uniform(0, 10); } Not so simple, unfortunately. Actual code: import std.random; struct Mystruct { auto id = uniform(0, 10); } void main() { // wahtever } ..and no luck. I think it is a bug: import std.stdio, std.random; struct Mystruct { //mixin(`auto id = uniform(0, 10);`); // Error: static variable initialized cannot be read at compile time int val; } void main() { Mystruct test; test.val = uniform(0, 10); // OK writeln(test.val); mixin(`auto n = uniform(0, 10);`); // OK }
Re: std.random question
On Sunday, 3 May 2015 at 08:42:57 UTC, tired_eyes wrote: Feels pretty silly, but I can't compile this: import std.random; auto i = uniform(0, 10); DMD spits this: /usr/include/dmd/phobos/std/random.d(1188): Error: static variable initialized cannot be read at compile time /usr/include/dmd/phobos/std/random.d(1231):called from here: rndGen() /usr/include/dmd/phobos/std/random.d(1231):called from here: uniform(a, b, rndGen()) Perhaps I'm missing something obvious? dmd 2.067.1, openSUSE 13.2 x64 void main() { import std.random; auto i = uniform(0, 10); }
Re: Classes. C++ to D
On Sunday, 3 May 2015 at 17:46:54 UTC, Meta wrote: This is not really doable right now in D. You can forward the function calls to a and b easily enough, but you can't inherit from more than one class. Once the multiple alias this patch gets merged you will be able to do this in D. On Sunday, 3 May 2015 at 18:17:26 UTC, Adam D. Ruppe wrote: I'd make class A and class B into mixin templates instead. mixin template A { string a() { return foo; } } mixin template B { string b() { return bar; } } class C { mixin A; mixin B; } If you still need class A and class B, just make a class that mixes in the template for them too. Since the C++ methods aren't virtual, I imagine you don't really need a base class for them, but if you do want a virtual base class, make interfaces and inherit from as many of them as you need. Thanks. On Sunday, 3 May 2015 at 20:03:00 UTC, QAston wrote: If you want to learn a language properly, translating the idioms directly from what you already know is a bad approach. You're going to be frustrated that something was easy (to you) in your old language and the new one is weird and different than the old one. Also - results are often suboptimal. I've seen this happen too many times to not warn you, but if you just want to carry over and you don't care about learning or quality of result then please carry on. At the moment, I do not do a complete study of the D, so the quality is not important to me. Start a complete study of D, I plan a little later.
Re: What wrong?
On Monday, 4 May 2015 at 01:03:43 UTC, Fyodor Ustinov wrote: I'm not sure that it's not my fault. So I hope that will come by knowledgeable people and say Hey, buddy, your mistake is... :) OK. But if one does not come within three days :), duplicate topic in this section: http://forum.dlang.org/group/digitalmars.D
Re: Ada to D - an array for storing values of each of the six bits which are sufficient
On Sunday, 3 May 2015 at 14:49:55 UTC, Martin Nowak wrote: On Friday, 1 May 2015 at 23:22:31 UTC, Dennis Ritchie wrote: Maybe someone will show a primitive packed array. I really can not imagine how to do it on D. Look at BitArray for an example https://github.com/D-Programming-Language/phobos/blob/12187d7be8b15b2f5f8ff6889cdb5ea3afb93dd1/std/bitmanip.d#L702. Here is an implementation in C++ that could be easily adopted. http://pempek.net/articles/2013/08/03/bit-packing-with-packedarray/ Thank you. This should help.
Classes. C++ to D
Hi, How can I rewrite this code to the D? - #include string #include iostream class A { public: std::string a() { return std::string(foo); } }; class B { public: std::string b(){ return std::string(bar); } }; class C : public A, public B {}; int main () { C c; std::cout c.a() c.b() std::endl; return 0; }
Re: What wrong?
On Saturday, 2 May 2015 at 02:51:52 UTC, Fyodor Ustinov wrote: Simple code: http://pastebin.com/raw.php?i=7jVeMFXQ This code works compiled by DMD v2.066.1 and LDC2 (0.15.1) based on DMD v2.066.1 and LLVM 3.5.0. $ ./z TUQLUE 42 11 Compiled by DMD v2.067.1 the program crashes: $ ./aa TUQLUE Segmentation fault What I'm doing wrong? I think the problem is in these lines: - receive( (supervisorAnswer a) = r = a.ret ); Partially it works :) - import std.variant; private struct Exit{}; private struct supervisorAnswer { Variant ret; } private __gshared Tid supervisorTid; private void supervisor() { static Variant[string] zval; bool done = false; void _store(T)(string k, T v) { assert(k.length 0); zval[k] = v; } void _get(Tid id, string k) { id.send(supervisorAnswer(zval.get(k, Variant(NOTFOUND; } while (!done) { supervisorAnswer answer; receive( (Exit s) { done = true; }, _store!long, _store!ulong, _store!int, _store!uint, _store!float, _store!double, _store!string, _store!Variant, _get, (Variant e) { writeln(e); }, ); } } Variant Get(const string s) { Variant r; supervisorTid.send(thisTid, s); writeln(TUQLUE); /*receive( (supervisorAnswer a) = r = a.ret );*/ writeln(42); return r; } void Set(T)(const string s, T v) { supervisorTid.send(s, v); } shared static this() { supervisorTid = spawn(supervisor); } shared static ~this() { send(supervisorTid, Exit()); } void main() { Set(1, 11); writeln(Get(1)); send(supervisorTid, Exit()); thread_joinAll(); }
Re: What wrong?
On Saturday, 2 May 2015 at 19:38:01 UTC, Fyodor Ustinov wrote: I see it by the lack of 42. :) But why is this receive breaks down? Report, please, about it (D)evepopers :) https://issues.dlang.org/
Re: Ada to D - an array for storing values of each of the six bits which are sufficient
On Friday, 1 May 2015 at 23:22:31 UTC, Dennis Ritchie wrote: Maybe someone will show a primitive packed array. I really can not imagine how to do it on D. Maybe you can somehow use bitfields. While what happened is something like this: - import std.stdio, std.bitmanip; struct A { mixin(bitfields!( uint, bit, 6, bool, flag1, 1, bool, flag2, 1)); } void main() { A obj; int[] a; foreach (e; 0 .. 64) { obj.bit = e; a ~= e; } writeln(a); // obj.bit = 64; // Value is greater than //the maximum value of bitfield 'bit' } - http://ideone.com/Opr4zM