Foo:
It seems that your code doesn't work with 2.065.
Right. For 2.065 you have to replace the enum expression with a
template.
If you can I suggest to update your compiler to the latest beta.
There are tons of bugfixes and changes.
Bye,
bearophile
mixin template Vala2(uint count, alias arr) {
What about disallowing mixin templatename unless you add
mixin before the template keyword?
Bye,
bearophile
Foo:
I do not understand?
Sorry, mine was a language design question (to catch your bug).
Bye,
bearophile
Uranuz:
ubyte a = 15;
ubyte b = 10;
ubyte c = a + b; //What is happening there?! ARGH! Are you
joking?!
In C/C++/D if you sum a types that are smaller than int, you
obtain an int. D has copied C for backwards compatibility with C
code.
Bye,
bearophile
Matthieu:
Can someone explain to me how to do it well, please?
Put related stuff in a module, and unrelated stuff in other
modules. If the module grows too much, split it up in two or
more. It's about the same as in Python. Just remember that
classes can see each other private members only
Matthieu:
Thanks for your answers. I'll continue to code as I ussed to do,
and try to improve my style to have a better usage of the
modules
(today i'm most one class per file, so I don't use the modules
at all).
Also, try to use less classes and more free (pure) functions :-)
This means a
Dicebot:
Probably most idiomatic D way is to use files _instead_ of
classes :)
It is a bit idealistic though and is not yet 100% feasible in
practice.
What's stopping it from being feasible?
Bye,
bearophile
H. S. Teoh:
It's already in std.typecons.
But it is not online yet?
Bye,
bearophile
Marc Schütz:
import std.stdio, std.zip, std.file, std.mmfile;
int main()
{
auto mmfile = new MmFile(File(c:/test.zip, rb));
auto zip = new ZipArchive(mmfile[]);
foreach (item; zip.directory) {
writeln(processing , item.name, ...);
// processing item...
}
return 0;
}
This
Archibald:
Any rational explaination to this? ( Seems unrelated to garbage
collection )
Not nearly enough info to answer. It looks fishy.
Bye,
bearophile
Dean:
I need a little helping hand with dmd on a 32 bit Debian box.
I
installed dmd from http://d-apt.sourceforge.net/
i) First trial:
$cat test.d
import std.stdio;
void main() {
writeln(hello);
}
$ time dmd test.d
real0m2.355s
user0m1.652s
sys
Dean:
Mine is an Athlon 1045.456 MHz. The minimum of 3 consecutive
compilation runs that I get is 2.3 seconds.
Then I think your timings could be OK, I am using an old 2.3 GHz
CPU.
On my box this compiles in 1.2 seconds. So it seems somewhat
consistent (as in 3 times slower for both).
Dean:
dmd compiles very quickly, but to compile writeln D has to
digest a good amount of Phobos code.
Are the reasons for this similar to why C++ STL is not an object
code library ?
The reasons for the large amount of code compiled for a writeln
are that: writeln is more powerful, Phobos
ddos:
auto twice = function (int x) = x * 2;
function is not necessary. And generally it's better to assign
to immutables, unless you need to mutate the variable twice
later.
how can i apply the function to each element in a without using
a forloop? - is there a function to do this?
ddos:
how do i add the elements in a and b elementwise
Several ways to do it:
void main() {
import std.range, std.algorithm, std.array;
immutable a = [1, 2, 3, 4];
immutable b = [2, 3, 4, 5];
int[] c1;
c1.reserve(a.length); // Optional.
foreach (immutable x,
Justin Whear:
By this do mean replacing the template constraint `if
(isInputRange!R)`
syntax? If so, we need concept definition syntax, but we do not
necessarily need a struct realizes concept syntax. And, in
fact, I
would argue against it as a static assert would continue to be
Sean Campbell:
i have the following code
char[] Etag(string file){
auto info = DirEntry(file);
ubyte[16] hash = md5Of(to!string(info.timeLastAccessed.day)~
to!string(info.timeLastAccessed.month)~
Kagamin:
Seems like a popular issue.
Y
es, it is.
Is there a bug report for it?
Bug report for what? To ask for [] to be used when you slice a
fixed size array? This is in Bugzilla. Or perhaps you are asking
for lifetime management of the data? This is currently discussed
in the main D
Kagamin:
Report for the problem when a temporary fixed-size array is
assigned to a slice, which is escaped.
I think this is already in Bugzilla. But the point is: you can't
solve this problem locally and with small means. You need a
principled solution (or no solution at all, as now) of
Klb:
Hello, I'd like to know if it's possible, using CTFE, mixin etc
to convert a POD struct to a class at compile time.
I remember Andrei planned to add this small thingie to Phobos,
but it's still missing.
Bye,
bearophile
Ary Borenszweig:
When assigning a fixed size array to a slice, can't you just
allocate memory and copy the data there (I mean, let the
compiler do that in that case)? That would be safe, right?
Yes, using a .dup:
char[] hashstring = toHexString(hash).dup;
But the compiler should not do
pgtkda:
How can i read the whole file if i use this:
File(C:\\Users\\text\\Desktop\\test.csv, r);
In std.file there are two functions to read a file or read a text
file, named read and readText.
Bye,
bearophile
Alexandre:
return (retVal 0x00FF) 24 |
(retVal 0xFF00) 8 |
(retVal 0x00FF) 8 |
(retVal 0xFF00) 24;
See also core.bitop.bswap.
Bye,
bearophile
Alexandre:
Thanks, but, when I convert I recive a 'c' in the front of my
number...
This shows it inverts all bits, not just the four byte positions.
I don't understand:
import core.bitop: bitswap;
uint reverseBytes(in uint val) pure nothrow @safe @nogc {
return val.bitswap;
}
void
Alexandre:
RefCounted!(DWORD) addr;
I think RefCounted is for advanced usages in D :-)
template Wrap(T)
{
struct Wrap
{
T val;
this(T val){val = val;}
}
}
Simpler:
struct Wrap(T) {
T val;
this(T val_) { this.val =
Alexandre:
as rc is better for managing scarce resources like file handles.
File instances are ref counted in D. Is this useful for you?
Bye,
bearophile
Alexandre:
mapstring, Address syms;
If you don't need the key ordering then use a built-in
associative array:
Address[string] syms;
Otherwise use a RedBlackTree from std.container.
vectorpairDWORD, Address values;
vectorpairDWORD, shared_ptrDWORD addrs;
Tuple!(DWORD, Address)[]
Nordlöw:
Could someone elaborate shortly which cases this means?
All cases where you really can't live without it :-) It's like a
cast(.
Bye,
bearophile
Klb:
...and any example where this switch will be usefull ?
I guess it was added to D in the spirit of If you have to ask
what it is, then you don't need to use it.
More seriously, I too would like more documentation about its use
cases.
Bye,
bearophile
Ola Fosheim Grøstad:
On Sunday, 13 July 2014 at 20:55:25 UTC, bearophile wrote:
D doesn't carry the range of mutable variables across
different expressions.
What is the reasoning behind this kind of special-casing?
Compiler simplicity and to avoid flow analysis. The value range
is kept
Andrea Fontana:
Is there any counter-indication with this:
immutable ubyte[5] stub = xb8 01 4c cd 21.representation;
?
See:
https://issues.dlang.org/show_bug.cgi?id=10454
https://issues.dlang.org/show_bug.cgi?id=5909
Is it a compile time value?
Generally you need module-level values or
Alexandre:
I get a lot of problens, to convert 'strings' to UCHAR... :/
I suggest you to take a look at the D docs and understand what D
fixed-sized arrays are, dynamic arrays, and strings (that are
dynamic arrays).
Bye,
bearophile
Alexandre:
BYTE[8] Name;
Generally in D field names start with a lowercase (unless you
need them with uppercase).
Btw, my problem is, how to acess the union elements ?
I try this:
//...
scth[0].Misc.VirtualSize = 15;
//...
But, the compiler return that error:
Generally in D field names start with a lowercase (unless you
need them with uppercase).
And user defined type names start with an upper case. This is
useful, because if you write:
scth[0].Misc.virtualSize = 15;
You see immediately that Misc is not a value but a type. So it
can't work.
Alexandre:
Look the complete code:
https://gist.github.com/bencz/3576dfc8a217a34c05a9
I know, has several things that can be improved
memcpy(dosh.e_magic, MZ.ptr, 2);
memcpy(peh.Signature, PE\0\0.ptr, 4);
memcpy(scth[1].Name.ptr, .idata.ptr, 6);
memcpy(scth[2].Name.ptr, .data.ptr, 5);
Alexandre:
void InjectData(T)(ref T BaseSrc, string data)
{
memcpy(BaseSrc, data.ptr, data.length);
}
It's possible to improve this function ?
You can add some modifiers (like @nogc for dmd 2.066), and the
name of D functions starts with a lower case.
Bye,
bearophile
Nordlöw:
Is there a natural way of generating/filling a
string/wstring/dstring of a specific length with random
contents?
Do you mean something like this?
import std.stdio, std.random, std.ascii, std.range, std.conv;
string genRandomString(in size_t len) {
return len
.iota
Brad Anderson:
Alternative:
randomSample(lowercase, 10, lowercase.length).writeln;
From randomSample docs:
Selects a random subsample out of r, containing exactly n
elements. The order of elements is the same as in the original
range.
Bye,
bearophile
Nordlöw:
I was specifically interested in something that exercises
(random samples) potentially _all_ code points for string,
wstring and dstring (all code units that is).
That's harder. Generating all uints and then testing if it's a
Unicode dchar seems possible.
Bye,
bearophile
Nordlöw:
I believe defining a complete random sampling of all code units
in dchar is a good start right? This can then be reused to
lazily convert while filling in a string and wstring.
Several combinations of unicode chars are not meaningful/valid
(like pairs of ligatures). Any thing that
Nordlöw:
https://github.com/nordlow/justd/blob/master/random_ex.d#L53
Isn't @trusted mostly for small parts of Phobos code? I suggest
to avoid using @trusted in most cases.
Bye,
bearophile
The idea of not making std.algorithm.among!() a predicate was not
so good:
void main() {
import std.stdio, std.algorithm;
auto s = hello how\nare you;
s.until!(c = c.among!('\n', '\r')).writeln;
}
(A normal workaround is to use !!c.among!).
Bye,
bearophile
Timon Gehr:
It works with filter, so I think it should just work with until
as well.
So do you suggest me to open a bug report where I ask among to
return a bool, or do you suggest to ask for an enhancement of
until, or what?
Bye,
bearophile
Danyal Zia:
I noticed that in Andrei's talks and his book, he used braces
on the same line of delcaration, however Phobos and other D
libraries I know use braces on their own line.
Rosettacode D examples always use the Egyptian style. For my code
I use the same style, but Phobos
Timon Gehr:
I am saying the following code implementing 'until' in
std.algorithm is at fault:
private bool predSatisfied() // -- don't say bool here
{
static if (is(Sentinel == void))
return unaryFun!pred(_input.front); // or cast here
else
Alexandre:
WORD e_res[4];
In D it's better to write:
WORD[4] e_res;
char image[0x800];
Note this is a thread-local variable. If you need a module-local
variable you have to write:
__gshared char[0x800] image;
void main(string[] args)
If you don't need the args, then
Marc Schütz:
Better use `ubyte[0x800] image` here. `char[]` is only for
UTF-8 strings.
Right, sorry.
Bye,
bearophile
Meta:
It seems that not even that is the case.
void main()
{
uint n = 0;
//Error
bool b = n;
}
D doesn't carry the range of mutable variables across different
expressions.
So write (with the 2.066beta3):
void main() {
const uint x1 = 0;
const uint x2 = 1;
Alexandre:
When the PE file is generate in EXE have just the M of MZ...
Let's try again, is this better?
import std.c.windows.windows: WORD, LONG;
struct IMAGE_DOS_HEADER {
WORD e_magic = ('M' 8) + 'Z',
e_cblp,
e_cp,
e_crlc,
e_cparhdr,
In case you have missed the thread:
http://www.reddit.com/r/programming/comments/2ag8qe/the_constness_problem/
Bye,
bearophile
pgtkda:
How can i get the number of items which are currently hold in a
DList?
Try (walkLength is from std.range):
mydList[].walkLength
Bye,
bearophile
Ary Borenszweig:
So the doubly linked list doesn't know it's length? That seems
a bit inefficient...
Have you tried to compile mydList.length or mydList[].length? If
both don't compile, then you have to walk the items.
Walking the items is not efficient, but:
- Linked lists are very
Rikki Cattermole:
int myint = to!int(4 ~ 7 ~ 0 ~ 1);
And to concatenate them there is join (joiner is not yet usable
here, because to!() doesn't yet accept a lazy input,
unfortunately).
Now they are not strings, and the positions of 10^ doesn't
change then:
int myint = (1000 * 4) +
Alexandre:
I want to know if have a more better way to make this... maybe
using lambda or tamplates
Your code is not bad. This is a bit better (untested):
void main() {
import std.stdio;
import std.conv: to;
auto lines = oi.txt.File.byLine;
int tot = 0;
foreach
Mike Parker:
Is it safe to assume that __VERSION__ is the same among DMD,
LDC and GDC when using the equivalent front-end?
Right. An alternative solution is to use __traits(compiles) and
use @nogc inside it.
Bye,
bearophile
Larry:
Now the performance :
D : 12 µs
C : 1µs
Where does the diff comes from ? Is there a way to optimize the
d version ?
Again, I am absolutely new to D and those are my very first
line of code with it.
Your C code is not equivalent to the D code, there are small
differences, even
Larry:
@Bearophile: just tried. No dramatic change.
import core.memory;
void main() {
GC.disable;
...
}
That just means disabling the GC, so the start time is the same.
What you want is to not start the GC/runtime, stubbing it out...
(assuming you don't need the GC in your program).
I
NoUseForAName:
In C my favorite way of achieving encapsulation is to use
incomplete types. The module header contains the definition of
an incomplete type and the prototypes for the public functions
which operate on it.
Probably in D you can archive something similar with different
means.
NoUseForAName:
Thanks.. but this is awkward. I expected there to be keywords
to declare type declarations public or private.
The keywords are public and private.
I guess I am going to stick with C for this.
I suggest you to not give up yet. About 100% of the times there
are equivalent
H. S. Teoh:
This looks pretty serious. Please file a bug:
http://issues.dlang.org/
I have filed it myself, as major:
https://issues.dlang.org/show_bug.cgi?id=13073
Bye,
bearophile
Ali Çehreli:
1) Put the opaque type and its functions into a .di file:
[...]
It seems your answer has scared NoUseForAName off. Next times we
need to be more careful, and suggest a D-idiomatic solution
instead.
Bye,
bearophile
Marc Schütz:
Instead, you can use a public alias to a private type:
// my_module.d:
private struct MyStructImpl {
int x;
}
public alias MyStructPtr = MyStructImpl*;
void doSomething(MyStructPtr foo) {
...
}
// my_main_program.d:
MyStructPtr bar;// OK
MyStructImpl foo; //
NoUseForAName:
Thanks, that is what I was looking for.
Why do you need a public pointer type but private struct type?
Bye,
bearophile
seany:
Iwonder if you could as well define a class inside another
class. I dont know if it is theoritically at all a sensible
thing to do. Just asking the question.
You can nest them. But in some cases you also want to use the
static keyword.
Bye,
bearophile
NA:
Any ideas welcome.
Is this good enough?
void main() {
import std.algorithm: swap;
int[][][][] a =
[[[],
[],
[[0, 1], [0, 2]],
[[0, 0], [0, 3]]
],
[[],
[],
[[1, 1], [1, 2]],
[[1, 0], [1, 3]]
Tobias Pankrath:
Use std.algorithm.sort with a custom comparison function.
It's a very nice example of learning algorithms and data fitting.
I have shown an answer very fitted (perhaps over-fitted) on the
given example. With just the given data there is no way to know
how much general the
Frédérik:
Especially I can't figure out how std.containers can connect
properly with std.ranges :
std.containers is still primitive, it needs to be improved and
fleshed out, after Andrei's memory allocators.
I would need to get the range that comes from the red black tree
(as returned by
Meta:
(a SortedRange needs a range with random access,
I think SortedRange was recently improved, and now accepts more
than just random access ranges.
Bye,
bearophile
Archibald:
Using std.algorithm.sort(a,b,c,d,e)
But isn't std.algorithm.sort accepting only one argument?
Bye,
bearophile
Brenton:
How would you recommend I do something like this with D?
In D compile-time constants are introduced using the enum
keyword.
You can also use the -version=... compiler switch to compile
your D code according to some version, that can be a number or
identifier.
In D there isn't
Sean Campbell:
I cannot figure out what is wrong with this code and why i keep
getting object.error access violation. the code is simple
tutorial code for SDL and OpenGL what am i doing wrong (the
access violation seems to be with glGenBuffers)
I don't know where your problem is, but you
Is this another bug in std.range.transposed?
void main() {
import std.stdio, std.algorithm, std.range;
auto M = [[[1, 2]], [[3, 4]]];
M.filter!(r = r.dup.transposed.walkLength).writeln;
M.filter!(r = r.transposed.walkLength).writeln;
}
Output with the latest dmd:
[[[1, 2]],
https://issues.dlang.org/show_bug.cgi?id=13041
Bye,
bearophile
Frustrated:
After upgrading to latest dmd, I get the follow error on the
code
template Array(T) { alias Array = std.container.Array!T; }
Try to use a different name inside the template, like Vector.
Bye,
bearophile
Frustrated:
Since there is no recursion going on there, it shouldn't be a
problem.
Yes, sorry.
In dmd 2.066 this too could work:
alias Array(T) = std.container.Array!T;
Bye,
bearophile
Dicebot:
Yep, I think it is D1 legacy approach. opBinary should be more
appropriate.
I hope the usage of the old operator overloading functions will
generate deprecation messages soon.
Bye,
bearophile
Puming:
is this a good practice to use `ref in` with structs instead of
traditional pointer syntax (which does not play well with UFCS
though) ? Is there any perfomance implications with `ref in`? I
tried that it does not seem to copy the parameter value,
A ref is equivalent to a pointer
Gecko:
is there a scanl like in haskell (like reduce but returning the
intermediate results as well).
Request in bugzilla, ma no Phobos pull request implementation yet.
Bye,
bearophile
Vlad Levenfeld:
Will there be a @nogc or @noheap flag in 2.066?
A @nogc. (The idea of @noheap was refused and I've closed down
the Enhancement request).
Bye,
bearophile
Sergey Protko:
libmpg123 has mpg123_init and mpg123_exit functions, which are
not thread-safe, so we should to call them only once per
process. Most of useful libraries also has such stuff. But
manual initialization is killing all beauty of high-level
bindings.
I think module static this
Puming:
I'm using scriptlike, which imports everything from std.process
for convienience, but I also need to import another module,
which contains a class `Config`, it conflicts with
std.process.Config. I don't actually need std.process.Config,
but I need many other symbols in scriptlike and
Stefan Frijters:
I found a pull request to add __traits(documentation, ...)[1]
which would also allow me to solve my problem as a workaround,
does anyone know if this is still moving forward?
You can state in that GitHub thread that you could use that
feature. There are many stalled nice
Nordlöw:
Is there an unqualified version of __FUNCTION__ that returns
just
treeContentId
instead of
fs.Dir.treeContentId
?
I suggest to use the string functions to strip the part you need.
Bye,
bearophile
John Colvin:
isn't this exactly what the System V ABI specifies anyway?
Large aggregate returns are allocated on the calling stack,
passed by hidden pointer.
So do you know why D is not using that design?
Bye,
bearophile
John Colvin:
It is,
As far as I know, D is using that as an optimization, not as an
ABI default that must happen at all optimization levels.
but a copy is made after the function returns anyway, for
reasons unknown to me. For some reason the optimizer can't
elide it (ldc2 -O5 -release,
Lemonfiend:
//list.linearRemove(tree); // -- Error. What is the correct
way?
}
---
linearRemove is linear, so I think it accepts a range. Perhaps
the once range is enough.
Bye,
bearophile
Sean Campbell:
but which one is better conforms to the d style?
Both are valid. Use the second when you want a more precise
exception in your code, this is common in larger programs.
Keep in mind that you can allocate an exception in a point and
throw it in another. This reduces the
seany:
int[string] k;
// populate k here
int[string] j;
foreach(sttring key, int val; k)
{
j[key] = val;
break;
}
This is OK, and you can encapsulate this into a little function.
But you are not removing the pair from the first associative
array. So you have to remove the item before
Danyal Zia:
Is there a way to check both versions at the same time? (I
can't seem to find the solution through google, sorry)
This is close to being the best solution in D (untested):
version(DigitalMars) enum myMars = true; else enum myMars = false;
version(LDC) enum myLdc = true; else enum
Is it possible and a good idea to change the D ABI to make code
like this avoid an array copy in 100% of the cases (without
inlining)?
ubyte[1000] foo() nothrow @safe {
typeof(return) data;
// some code here.
return data;
}
void main() nothrow {
immutable data = foo();
}
Is it possible and a good idea to change the D ABI to make code
like this avoid an array copy in 100% of the cases (without
inlining)?
I meant, letting the compiler rewrite that code like this:
void foo(ref ubyte[1000] __data) nothrow @safe {
__data[] = 0;
// some code here.
}
void
Tobias Pankrath:
Isn't this a case for Named Return Value Optimization?
Perhaps, but then why aren't dmd/ldc doing it? And the question
was if that's possible in the ABI, so it always happens (unless
the array is very small).
Bye,
bearophile
h_zet:
Problem solved, Thank you so much!
I don't think it's solved. There are probably bugs worth
reporting here.
Bye,
bearophile
I don't think it's solved. There are probably bugs worth
reporting here.
I have not found them, sorry for the noise.
Bye,
bearophile
John Colvin:
I'm getting OutOfMemoryErrors on some machines when calling
GC.malloc (or new) for anything large (more than about 1GB),
where core.stdc.malloc works fine.
I think that when you go in territories where most people have
not done much coding in D, like allocating than 1 GB in one
h_zet:
Why does this work? Or it is a bug?
When you play a little with this code it's easy to see _error_
that should not appear. So there's surely something worth
reporting as bug, but I don't yet know what.
Bye,
bearophile
Ary Borenszweig:
As a library solution I would do something like this:
Union!(int, string)[] elements;
elements ~= 1;
elements ~= hello;
Take a look at Algebraic in Phobos.
Bye,
bearophile
Uranuz:
bool isDigit(char c) nothrow
This function is already in Phobos, it's std.ascii.isDigit.
ushort hexValue(char c) nothrow
Better to use this signature (assuming you want a ushort result,
despite a ubyte suffices and a uint is faster):
ushort hexValue(in char c) pure nothrow
Uranuz:
But what @nogc changes in there so I should use this modifier?
@nogc will be present in dmd 2.066, it means that the function
(and all the functions it calls) can't perform operations that
cause a call to GC functions.
Sometimes GC operations are a source of performance loss.
Uranuz:
But I don't understand why in expression where both of
arguments have type char:
return c - '0';
I have resulting type int. It's very strange for me and looks
very buggy)
In D operations among chars return a int. The same happens in
C/C++.
If you subtract a char from a
301 - 400 of 520 matches
Mail list logo