Uranuz:
Another stupid question. Using this logic substraction for two
uint values should return int too, because it can produce
negative result. Am I right or not?
There are no stupid questions, there are only some stupid answers.
Generally uint - uint generates a result with a
Uranuz:
Why there are so complicated rules in the *new* language.
It's hard to understand the logic.
Despite D being only 14 years old, one of its rules is to
(usually) give the same results if you write code that is valid
in C. This means it has to follow many rules of C language. If
you
sigod:
Shouldn't keywords be disallowed for module names?
I agree. (Walter seems not too keen on strictness). This question
seems more fit for the main D newsgroup. Look in Bugzilla if
there is a enhancement request.
Bye,
bearophile
Paul:
IS there such method get(key, default) for associative arrays,
like in Python?
Try it.
Bye,
bearophile
Byron Heads:
Anyone seeing this error?
Assertion failure: '0' on line 423 in file 'backend\aa.c'
Please put in a new Bugzilla entry a minimal program that
generates that failure.
Bye,
bearophile
Jerry:
If I do
f.readf(%s %s, l, i);
it fails if the whitespace is a tab.
In you can use byLine, followed by a split, and then assignment
of the pieces, followed by to!int where necessary.
Bye,
bearophile
Paul:
class MyError : Exception {
this(string msg) { super(msg); }
}
Don't call exceptions errors, because in D there are also errors,
so they should have distinct names.
Is any shorter D way?
Perhaps not.
Bye,
bearophile
Juanjo Alvarez:
Probably I pretty simple question, how could I mark some code
to be compiled when in debug OR unittest mode? (or both, ||)
At first I tough I could do:
version(unittest, debug) {}
You can define a enum boolean value in the version unittest
block, and another inside the
Juanjo Alvarez:
Probably I pretty simple question, how could I mark some code
to be compiled when in debug OR unittest mode? (or both, ||)
Regarding your latest ER, Walter is usually not fond of such
ideas. I have seen many similar ideas being shot down.
Bye,
bearophile
Chris:
auto word = bla-bla;
auto parts = appender!(string[]);
w.splitter('-').copy(parts);
// parts.data.length == 3 [bla, , bla]
With the current dmd 2.066alpha this code:
void main() {
import std.stdio, std.string, std.algorithm;
const txt = bla-bla;
txt.split(-).writeln;
katuday:
I am very new to D.
Welcome to D :-)
alias the_row = string[];
alias the_table = the_row[];
Here you are defining two types (and in D idiomatically types are
written in CamelCase, so TheRow and TheTable).
File inFile = File(account.txt, r);
This is
Joseph Rushton Wakeling:
which version of the dmd frontend introduces support for the
notation T(n) to initialize a variable as type T? Is it 2.065
or the upcoming 2.066?
In 2.066.
Bye,
bearophile
John:
I can iterate over the struct elements with the traits
FieldTypeTuple!foo,
In such iteration you are using a static foreach. Types are
compile-time constructs in D. If you need run-time entities you
need to get their typeinfo.
I can iterate over the the string that represents the
John:
C:\D\dmd2\windows\bin\..\..\src\phobos\std\range.d(3808):
Error: template std.range.zip cannot deduce template function
from argument types !()((int, float),string[])
By the way, I find it surprising that D/Phobos give a so good
error message for a so messed up situation. I don't
Mark Isaacson:
My attempts to have either the MinGW linker or the Visual Studio
linker accept my D .objs have all failed.
Try using the dmc compiler for the C code.
Bye,
bearophile
Ali Çehreli:
Here is a workaround:
unittest {
size_t delegate()[size_t] events;
auto makeClosure(size_t i) {
return { return i; };
}
foreach( i; 1..4 ) {
events[i] = makeClosure(i);
}
You can also use two lambdas to do that, without the
makeClosure:
Etienne:
Are asserts supposed to be evaluated in DMD release? I was
getting a privileged instructions error 0xC096 which was
caused by an assert, when doing some gc programming in druntime
assert(0) are not removed in release builds. They are a HALT.
Bye,
bearophile
Vlad Levenfeld:
Is there any way that I can detect whether or not a function is
being evaluated at compile time? Specifically I want to switch
between to use/not to use memoize!func without having to figure
out when its CTFE-able and calling it with different syntax.
Calling it with a
Atila Neves:
D:
struct Foo { int i; int j; }
extern(C++) void useFoo(ref const(Foo) foo);
C++:
struct Foo { int i; int j; };
void useFoo(const Foo foo) { ... }
This doesn't look very safe because D const is transitive, unlike
the C++ const. So in the C++ code you can
Martin Krejcirik:
float a = 1.23f;
double b = to!float(1.23);
assert (a == b); // ???
}
Should the assert fail or not ? (Please reply without trying
first).
It's a bad question. Generally to compare floating point values
for equality use std.math.feqrel.
Bye,
bearophile
matovitch:
Does anybody knows why dmd segfaults on this code ? Should I
report this as a bug ?
Please report this minimized case to Bugzilla:
struct Foo(int[] arr) {
const int[] arr = arr;
}
void main() {
Foo!([0]) foo;
}
The error it gives before the crash:
test.d(2,17):
Miles Stoudenmire:
In contrast to those two examples where immutable can be used
at compile
time, what are some other cases where it is necessary to use
enum instead of immutable?
By default use enum if you define a compile-time-known value,
unless it's composed data like an array, etc.
Chris Nicholson-Sauls:
Good... I was starting to fear I was the only one.
In general you can't fix the names in a language because you
always find someone that likes the ones present :) I think enum
is a bad name for the purpose of defining manifest constants, but
I don't think this will
francesco cattoglio:
And why is const(Foo) getQ so much different? (e.g: this is
an explicit cast, right?
In D the syntax for casts is cast(something)somethingElse.
Bye,
bearophile
Russel Winder:
For me, enum means create an enumerated type. Thus enum
double to define a single value is just a contradiction.
Enlightenment required…
In D enum can be used to define manifest constants. This means
constants known at compile time. In practice for a double there
isn't a
Philippe Sigaud:
as foo is returning a value from a private type, it should be
considered private also.
I think this was discussed, but I don't know why Walter didn't
design like that. Perhaps someone else can give you an answer.
Bye,
bearophile
Remo:
is it also possible to save/write string at compile time?
There is pragma(msg, ...) but it's a little crappy. There are
plans and a pull request for a good _ctWrite, but it's stalled
for reasons unknown to me.
Bye,
bearophile
maarten van damme:
writeln(providor_symbol_map.keys.sort!((x,y)=providor_symbol_map[x].length=providor_symbol_map[y].length));
[/code]
Try:
((x, y) = providor_symbol_map[x].length
providor_symbol_map[y].length)
Bye,
bearophile
Wanderer:
providor_symbol_map.sort!((x,y)={x.value.length=y.value.length}),
This lambda doesn't return a boolean. Also, add spaces around
operators and after commas.
Bye,
bearophile
Dicebot:
It is also because `malloc` can return null when out of memory
and `new` will throw an Error. Wrapper around `malloc` that
throws `OutOfMemoryError` on null can be considered of same
purity class as `new`.
One wrapper should have a template argument to specify the type
of the
I don't know if this is a bug, an enhancement request, or just a
mistake of mine. I don't understand why currently @nogc refuses
this code:
import std.algorithm: filter;
struct Foo {
bool bar(in int) @nogc {
return true;
}
auto spam() @nogc {
immutable static data
Chris:
The following:
import std.stdio;
void main() {
int[5] arg;
arg[10] = 3; // Compiler says (of course):
Error: array index 10 is out of bounds arg[0 .. 5]
}
import std.stdio;
void main() {
int[5] arg;
foreach (i; 0..10) {
arg[i] = i;
}
}
Compiler says
Nicholas Londey:
So I tried rewriting the example on the dlang.org home page and
came up with the following.
import std.algorithm, std.exception, std.stdio;
double average(T)(T range)
{
enforce(!range.empty, No inputs);
auto totals = range.map!(a = tuple(1.0,
Stefan Frijters:
Is this by design? It was very surprising to me, especially
since all other combinations do seem to work.
I don't know if this situation is by design. At first sights it
seems a limitation that could be removed.
Bye,
bearophile
Alexandr Druzhinin:
In D code I do
void* data = GC.malloc(...);
if(data is null)
...
In C code I do
void* data = malloc(...);
if(data == null)
...
What to do when in D code I have
void* data = std.c.stdlib.malloc(...);
if(data ?) // is null vs == 0
x is null or x == null are
Adam D. Ruppe:
but I prefer is null because that is most consistent with
other D code (where there might be a difference between the
two).
Curiously I do the opposite, I use == to remind me it's a pointer
:-)
Bye,
bearophile
Darren:
Let's say I have a hex representation of a large number:
String hexnum = 16D81B16E091F31BEF;
I'd like to convert it into a ubyte[]
A simple way is to use hex strings and then cast it to
immutable(ubyte)[]:
void main() {
immutable hexNum =
Andrew Brown:
I would like to write a double to a text file as hexadecimal
and then read it back in without losing information.
Is this good enough for you?
void main() {
import std.stdio, std.math;
auto fout = File(ouput.txt, w);
fout.writef(%a, PI);
fout.close;
auto
Meta:
You need to use the function array from std.array.
import std.array;
int[] source = [ ... ];
int[] sample = randomSample(source, 3).array();
In some cases it's also useful to use std.algorithm.copy:
void main() {
import std.stdio, std.algorithm, std.random, std.array,
Steffen Wenz:
Just noticed that using UFCS does not work for nested functions,
Right.
and was wondering whether that's intended, and what the
rationale behind it is:
Currently it's intended. Because doing otherwise causes other
problems with struct/class member functions. Perhaps there
Tim:
is there any chance to modify a char in a string like:
void main()
{
string sMyText = Replace the last char_;
sMyText[$ - 1] = '.';
}
But when I execute the code above I'm always getting cannot
modify immutable expression at sMyText[__dollar -1LU]. I
though D supported such
John Colvin:
Any plans to get any preprocessor stuff working?
Do you mean in D?
Bye,
bearophile
There are of course ways to implement a really efficient ZLW
compressor in D, and such implementation could be added as
third D entry if it manages to be not too much long,
Third version added:
http://rosettacode.org/wiki/LZW_compression#More_Efficient_Version
I have tried to make it
Artur Skawina:
So how does it perform wrt the D version that I wrote for
you last time? [1]
[1]
http://forum.dlang.org/post/mailman.2132.1353592965.5162.digitalmar...@puremagic.com)
From your answer:
First, the code above is practically a textbook example on how
/not/ to
write readable and
Artur Skawina:
Ugh. So how does it perform wrt the D version that I wrote for
you last time? [1]
I have done a benchmark with the various version (the first 3 are
the ones on the Rosettacode site, and the #4 is yours):
lzw1: 0.39
lzw2: 0.17
lzw3: 0.21
lzw4: 0.17
I think your comment was
monarch_dodra:
Arguably, your code allocates a lot.
What version (1-2-3) do you mean?
I'll give it a shot (next week).
I think the LZW entries are OK :) So if you want to work on
Rosettacode it's better to write an entry that is missing in D.
Bye,
bearophile
This task asks for an basic implementation of the the
Lempel-Ziv-Welch (LZW) compression/decompression algorithm. I am
keeping two D versions, the first one is minimal, and the second
is a little more optimized:
http://rosettacode.org/wiki/LZW_compression#More_Refined_Version
There are of
monarch_dodra:
As a matter of fact, the built in sort property does it.
It's going to be deprecated soon.
Bye,
bearophile
Chris:
Is there any huge difference as regards performance and memory
footprint between the two? Or is 2. basically 1. under the hood?
An associative array is a rather more complex data structure, so
if you don't need it, use something simpler. There is difference
in both the amount of
Chris:
Do you mean the difference is negligible in many cases?
Yes, but you have to profile the code (or reason about it well,
with knowledge of the data structures and their usage patterns)
if you want to know what your case is.
Bye,
bearophile
Chris:
foreach (size_t i; 0..myArray.length) {
// do something with myArray[i];
}
There are various better ways to use a foreach on an array:
foreach (immutable x; myArray) {
foreach (ref const x; myArray) {
foreach (ref x; myArray) {
Bye,
bearophile
Damian Day:
Benchmark found here:
http://dpaste.dzfl.pl/0058fc8341830
Perhaps it's a problem of missed dmd inlining. So I suggest to
run the benchmark with ldc2.
Bye,
bearophile
Yuriy:
but I like D, and i strongly believe it's the next big language.
Oh, good. Do you want to briefly explain why? :)
Bye,
bearophile
Artur Skawina:
But I have no idea why anybody would want to wrap this trivial
expression like that.
And, I have no idea if the, hmm, /unconventional/ D offsetof
semantics
are in the bugzilla. It's not really a bug, but a design
mistake...
https://issues.dlang.org/show_bug.cgi?id=12714
amehat:
What is the proper behavior for this D?
D doesn't have that Java syntax, because it was widely regarded
as a Java design mistake. So in D omit the throws part. If your
function tree doesn't throw exceptions (but it can throw errors)
add a nothrow.
Bye,
bearophile
Jonathan M Davis:
I still think that allowing const on the left is simply a
bad design decision.
I opened a request on this, and it was closed down :-)
Bye,
bearophile
H. S. Teoh:
FWIW, for very long function signatures I write it this way:
const(T)[] myVeryLongFunction(T)(const(T)[] arr,
intx,
inty,
intz,
Yuriy:
But. Why are you protecting __monitors so eagerly? :)
Also take a look at the Rust language, that avoids some of your
problems :-)
Bye,
bearophile
So far in Rosettacode D entries I've kept a line length limit of
72 or 73 chars.
But now a little larger monitors are common, D UFCS chains are
common, and we also have longer function signatures with pure
nothrow @safe @nogc (that usually I put on a new line), so
keeping that line length
Nick Sabalausky:
72-73 chars would indeed be a pain. In my own code I like to
use a soft limit of 80, FWIW.
This is not regular code, it's an online wiki. The situation is a
little different. But I think 80 is now acceptable.
Bye,
bearophile
Mark Isaacson:
I'm trying my hand at reading from standard input and having
little luck. In particular, I would like to be able to do the
rough equivalent of C++'s:
cin myString;
There isn't always a 1:1 mapping between C++ and D. In D if you
want a single word you usually read the whole
Mark Isaacson:
Fair enough. I've done stuff like that in the past. I'm trying
to implement a university project that was originally designed
for C++ style I/O... and so where I'd have otherwise jumped at
something like that from the beginning, my hands are slightly
tied.
If you need/want
Mark Isaacson:
Indeed. However, doing so looks more painful than redefining my
goals. Upon further examination it seems that I had more
flexibility than I originally estimated. Besides, the real
reason I'm implementing this project is just to practice for
when I get to write production D
Is it a good idea to add a function like this to Phobos?
This is just a first draft of the idea.
void main() {
import std.stdio, std.algorithm, std.range, range_matcher;
auto primes = iota(2, uint.max)
.filter!(x = iota(2, x)
.all!(t =
Artur Skawina:
Keep in mind that D's offsetof is flawed - if the object does
not contain the requested member, but implicitly converts to
another one that does have such field then the expression
compiles, but yields a bogus value. Eg
struct S { int a, b, c; S2 s2; alias s2 this; }
Artur Skawina:
And, I have no idea if the, hmm, /unconventional/ D offsetof
semantics
are in the bugzilla. It's not really a bug, but a design
mistake...
Design mistakes are valid bugzilla entries. At worst the bad
behavior could be documented. But often it's possible to fix the
design
H. S. Teoh:
Exercise for the reader: spot the bug.
https://issues.dlang.org/show_bug.cgi?id=5212
https://issues.dlang.org/show_bug.cgi?id=11657
Bye,
bearophile
Andrey:
A similar D code is, as far as I know,
type.field.offsetof
Yes, it's a built-in feature of D.
Is there an any way to make a corresponding D template?
I don't understand. Please explain better.
Bye,
bearophile
Chris Piker:
Is there any way to get a list of the properties and functions
provided by a module or class or generic variable in D at
runtime?
In D there are various traits to do that a compile-time. Like:
http://dlang.org/traits.html#allMembers
There are also the Phobos traits:
Andrej Mitrovic:
I can do this:
struct Foo(T) { }
template bar(T : Foo!int) { }
I can check if T is a specific instantiation of Foo. But I want
to
check whether T is *any* instantiation of Foo. Is this possible
to do?
There is now std.traits.isInstanceOf that could do what you need.
Its
monarch_dodra:
As rule of thumb, you can't allocate during a GC cleaning
cycles, and class destructors are usually called during a GC
cleaning cycle.
This means it is usually unsafe to call *anything* that could
potentially allocate in a destructor.
So it could be a good idea to have
Jonathan M Davis:
Andrei suggested auto ref to fix this problem, and Walter
implemented it, but he misunderstood what Andrei had meant,
I missed this detail of the story :-)
Walter has suggested that we just redefine ref itself to do
what I just
described rather than using auto ref or
Alex:
Why the compiler does not complain or,
I've just asked something related to this in the main D
newsgroup, take a look there for answers. Today D has means to
complain statically.
But I don't know the fate of D class destructors.
Bye,
bearophile
Mark Isaacson:
2) Create a wrapper struct that contains key and value and
whose comparison operator is defined only on the key. This
would essentially be doing what the C++ implementation does.
Until we have a tree-based associative map, use a tuple for the
key-value and define a less
Mark Isaacson:
Got it, no native support. Most unfortunate.
What native support are you talking about?
I've always been vehemently against losing self-documentation
via the std::pair/tuple based solution to the problem.
What self documentation are you losing in D?
I ended up rolling my
Dicebot:
What benefits this gives over definining distinct struct?
Sounds like unnecessary complication for me.
See the code in my precedent post, what do you think about it?
Bye,
bearophile
Mark Isaacson:
Accordingly, I no longer need an answer to my second question
unless someone knows of a more idiomatic way to get the same
results.
Is the alias this useful in this case?
Bye,
bearophile
Jonathan M Davis:
If you want it to be guaranteed, you'd do something like
template foo(string s)
{
enum foo = s ~ betty;
}
A more general solution is to wrap the concatenation with a call
to:
alias ctEval(alias expr) = expr;
Use:
string bar() { return ctEval!(s ~ betty); }
Bye,
Nordlöw:
How can I make `join` variadic (by filling in njoin) in the
following code?
When you have a D tuple (not Phobos tuple), and it contains
values all of the same type, you can turn it into an array with
just:
[mytuple]
Once you have an array of strings, you can use the normal
brad clawsie:
auto digest = HMAC(EVP_sha1(),
cast(void *) key,
Better to attach the * to void.
cast(int) key.length,
cast(ubyte*) s,
Here you are casting a struct of pointer to immutable plus length
to a
ketmar:
so it's broken beyond any repair. so sad.
The current implementation of the module system has some
problems, that are being worked on. If you think some part of the
module system design is not good enough, then try to ask for an
enhancement :-) No need to be sad.
Bye,
bearophile
Artur Skawina:
The D module system has a lot of problems and certainly needs
to be completely redesigned from scratch,
I don't think it will be redesigned from scratch (and if that
happens I see no proof that the redesign will be better than the
original design). So better to fix its major
ketmar:
ah, i can't clearly express myself even in this case, i don't
think i can make clear request. it's easier to write code, not
words. ;-)
i'm sad not about D or module issues, i'm sad about myself.
One of the most important skills of a programmer (and of course a
technical/literary
ketmar:
the thing is that English neither my native language
Nor mine, as you can see :-) And I am bad with natural languages
in general. But you can learn to write acceptable English if
you do exercises for some years :-)
Bye,
bearophile
Andrey:
Could anyone please explain to me, why do I have error message
on this piece of code?
In this thread you are doing some mistakes. This code seems OK:
alias TData = short;
alias TArray = TData[100];
struct MyStruct {
TArray* arrPtr;
}
void main() {
MyStruct* t3 = new
Chris:
I need an array that contains pointers to types created via
template. To stick to my usual example:
Person!(string)
How can I make an array with pointers to concrete instances
of Person!(string)?
Every template creates a new type, so you can't put them as they
are in an array.
Chris:
So there is no way of filling an array with something like
Person!(string) *pptr;
foreach(person; people) {
buf ~= person;
}
So you want an array filled with instances of the same
instantiation, sorry, I misunderstood your problem for a more
complex one :-)
Bye,
bearophile
Andrey:
alias short Type1;
The alias X Y; syntax is going to be deprecated, so use alias
Y = X; if your compiler already supports it.
alias Type1[100]* Type2; // if I take out '*' I will have to
type it everywhere, because arrays in D2 always 'by value'
Adding the * everywhere could be
spec:
Although, yeah, it would be nice if the compiler emitted some
kind of warning pointing this (if it's at all possible). What
got me confused was indeed the disparity of results from
changing small things.
If you think this can be done and it's useful, then ask for this
enhancement
Lazy arguments in general allocate, but who is to blame for the
allocation?
Isn't the allocation at the calling point?
This code:
void foo(lazy int x) @nogc {
auto r = x(); // Error
}
void main() {
foo(1);
}
Gives:
test.d(2,15): Error: @nogc function 'test.foo' cannot call
spec:
Although, yeah, it would be nice if the compiler emitted some
kind of warning pointing this (if it's at all possible). What
got me confused was indeed the disparity of results from
changing small things.
D doesn't like warnings, but it could be an error. This is
minimized code:
Dicebot:
It happens because attribute inference does not work properly
on generated delegated for lazy argument. I think it is a bug
lazy int x is effectively same as int delegate() x and
@nogc states that you can only call other @nogc functions and
delegates from something annotated as
spec:
I usually try to refrain myself from opinionating on stuff
where i lack proper knowledge and i'am still a newbie with D
(contrary to you bearophile).
It's not just a matter of experience, when there are many
interacting parts it's also a matter of intelligence (and people
like Timon
Meta:
I'm trying to create a basic List type using Algebraic, but the
compiler keeps complaining about recursive aliasing.
As stated in its docs, Algebraic is not yet finished and good for
recursive data structures. But here I have put an usage example
of that kind:
Meta:
alias List = Algebraic!(typeof(null), Cons!(int, This));
Also your Cons seems a value type, like Algebraic itself. You
have to avoid creating an infinite-size algebraic value.
Bye,
bearophile
Meta:
I should specify. This did not work:
alias T = Algebraic!(int, This*);
void main() {
auto l = T(1, new T(2, new T(3, null)));
}
An Algebraic is a sum type, so you can't store two value in it,
only one, an int or a T*. But this is not going to solve your
problems...
Bye,
Meta:
The more I try to use Algebraic, the more I come to think that
this is something that can't be done cleanly in a library, even
in D.
Algebraic is currently unfinished and needs improvements. If it
turns out it's not possible to implement it well in library code,
we can find the
If no one comment I'll put this in Bugzilla.
https://issues.dlang.org/show_bug.cgi?id=12667
Bye,
bearophile
They are not the same type:
void main() {
import std.typecons: Tuple;
alias T1 = const Tuple!(int, int);
alias T2 = Tuple!(const int, const int);
static assert(is(T1 == T2)); // Fails.
}
This type difference causes some troubles when you use tuples.
Bye,
bearophile
Dicebot:
Why would you even expect those to be same types? These 2 types
are also different:
struct A
{
const int x;
}
alias A_ = const(A);
In general a tuple is a higher level data structure compared to a
struct. So it's not unreasonable to expect a Tuple to be more
flexible than a
401 - 500 of 520 matches
Mail list logo