Re: Setting GTK_BASEPATH for gtkd

2023-10-16 Thread dan via Digitalmars-d-learn

On Monday, 16 October 2023 at 18:57:45 UTC, bachmeier wrote:

On Monday, 16 October 2023 at 18:28:52 UTC, dan wrote:

(Now, i still think that when module initialization order is 
not forced, it should be something a programmer or systems 
integrator can choose, but i don't want to be too greedy.)


Thanks again for your help!!

dan


I changed the subject line, so if case Mike Wey sees this, he 
knows it's about gtkd. If you haven't already, you make want to 
post your question at https://forum.gtkd.org/groups/GtkD/


Thanks Bachmeier.

It's not exactly a question anymore since Rikki clued me in on 
the crt_constructor pragma.


But i guess i should ask the gtkd forum if there's a better 
approach, or perhaps a way to set a hook into gtkd for 
pre-initialization activity (giving a program a chance to scout 
around for libraries or other resources before actually 
attempting to load anything).


dan


Re: Forcing my module to be initialized first

2023-10-16 Thread dan via Digitalmars-d-learn
On Monday, 16 October 2023 at 10:23:54 UTC, Richard (Rikki) 
Andrew Cattermole wrote:
Okay, after looking at gtkd, I don't think this can be solved 
with module constructors or swapping out to lazy initialization.


One way that might work however is to use a crt_constructor as 
that runs before the D stuff. However it would now hard code 
your program to your system. Over all my suspicion is that 
there is something wrong with your system related to library 
lookup paths and that should be fixed instead.


```d
void main() {
import std.stdio;
import std.process;
writeln(environment["GTK_BASEPATH"]);
}

pragma(crt_constructor) extern(C) void myEnvironmentVarSetter() 
{

import core.sys.posix.stdlib : putenv;
putenv(cast(char*)"GTK_BASEPATH=~/bin/gtk".ptr);
}
```


Really awesome, Rikki, your code does the trick.  Thank you so 
much for your pragma.



Since you are so right about the code, maybe you are also right 
about my system.  For reference, i'll describe it in case anybody 
else somehow wanders into the same situation.


My system is a Mac Catalina (OSX 10.15).

I installed the latest dmd i could find, directly from the 
Digital Mars website.  This was so that i could use any ports 
system (macports, fink, or brew) and keep the same d compiler.  
The dmd compiler is in /usr/local/bin/dmd, and the files are in 
some standard location 
/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/.


I installed the gtk stuff (but not gtkd) from macports, and that 
all went into /opt/local, which is where macports puts things.


I believe that gtkd does not have a 'configure' script, so i 
directly edited the top level GNUMakefile in one spot, to specify 
a prefix; my changed line was

prefix?=/opt/some-particular-path-distinct-from-local-and-all-others

I wanted the installation of gtkd to be in some parallel location 
so that there could be multiple versions if needed, or it could 
be removed if needed without any chance of disturbing macports or 
anything else.


It built ok, and the demo worked ok (setting GTK_BASEPATH of 
course, per gtkd's README.md).  Note that i built it on an 
account for which the PATH has /opt/local/bin and /opt/local/sbin 
at the start.  So when gtkd was under construction, it knew just 
where to find all the gtk files.


Thanks again for pointing out the crt_constructor pragma.

(Now, i still think that when module initialization order is not 
forced, it should be something a programmer or systems integrator 
can choose, but i don't want to be too greedy.)


Thanks again for your help!!

dan


Re: Forcing my module to be initialized first

2023-10-15 Thread dan via Digitalmars-d-learn

On Monday, 16 October 2023 at 04:26:32 UTC, Paul Backus wrote:

On Monday, 16 October 2023 at 03:31:13 UTC, dan wrote:
I have some code that i would like executed before anything 
else is.


The code is to set an environment variable which is used by a 
library.  I'm trying to find some way to avoid setting the 
environment variable on the command line, or in any shell 
script or initialization file.


I think the place to put such code would be in a 'static this' 
inside a module.


So i need some way to force my module to be initialized first, 
ahead of all others.


You may find this article enlightening:

https://devblogs.microsoft.com/oldnewthing/20050607-00/?p=35413


Hi Paul,

Thanks for the link.

It was funny, and for sure too many cooks spoil the broth.

I don't think that applies here, since i'm just trying to tweak 
the initialization order, and i'm the only programmer involved.


Of course, i guess all sinners try to justify their wrongdoing 
--- hope i'm not doing that here!!


Thanks for your reply.

:)

dan


Re: Forcing my module to be initialized first

2023-10-15 Thread dan via Digitalmars-d-learn
On Monday, 16 October 2023 at 03:33:55 UTC, Richard (Rikki) 
Andrew Cattermole wrote:

On 16/10/2023 4:31 PM, dan wrote:
I suppose if i could figure out a way to make all other 
modules depend on my module this would happen, but the module 
which uses the variable i want to set is in some 
already-compiled dynamic library that i would prefer not to 
touch.


If its in a shared library, then that shared library gets setup 
prior to your binary.


There is nothing that you can do. You gotta override rather 
than initialize.


Thanks Rikki.

I was wrong in my statement of the problem: it is not a dynamic 
library, but rather a static library, libgtkd-3.a.


I apologize for being so careless.

libgtkd-3.a throws an exception before main is reached, in the 
Loader.d file, in a method with signature 'public static void 
loadLibrary(string library)'.  That method is used trying to load 
a library which really is dynamic, libatk-1.0.0.dylib.  That 
library is in my system, among the Mac ports files, in a standard 
place, namely /opt/local/lib.  I can set the environment variable 
GTK_BASEPATH to help it out, and that works, but i would like to 
do all of this inside the executable rather than outside the 
executable.


The Loader.d file depends on std.process.

So, given that i was wrong and it is not a dynamic library i'm 
trying to get in ahead of, but a static one, is there a way to 
execute a small snippet of code after std.process is initialized, 
but before any other code (such as Loader.d) uses it?


Thanks in advance for any ideas.

dan


Forcing my module to be initialized first

2023-10-15 Thread dan via Digitalmars-d-learn
I have some code that i would like executed before anything else 
is.


The code is to set an environment variable which is used by a 
library.  I'm trying to find some way to avoid setting the 
environment variable on the command line, or in any shell script 
or initialization file.


I think the place to put such code would be in a 'static this' 
inside a module.


So i need some way to force my module to be initialized first, 
ahead of all others.


I suppose if i could figure out a way to make all other modules 
depend on my module this would happen, but the module which uses 
the variable i want to set is in some already-compiled dynamic 
library that i would prefer not to touch.


Alternatively, is there some entry point besides main that i 
could use, that executes before main and before any module 
initialization is done? (Is it possible to get in before the d 
runtime starts?)  Although i would prefer to code in d, it would 
be ok to do it in c.


This is on MacOS (Catalina) in case that makes a difference, and 
i'm using dmd v2.104.0.


Thanks in advance for any clues.

dan


Re: Want a function that determines a double or float given its 80-bit IEEE 754 SANE (big endian) representation

2023-08-23 Thread dan via Digitalmars-d-learn

On Wednesday, 23 August 2023 at 03:24:49 UTC, z wrote:

On Tuesday, 22 August 2023 at 22:38:23 UTC, dan wrote:

Hi,

I'm parsing some files, each containing (among other things) 
10 bytes said to represent an IEEE 754 extended floating point 
number, in SANE (Standard Apple Numerical Environment) form, 
as SANE existed in the early 1990s (so, big endian).


Note that the number actually stored will probably be a 
positive even integer less than 100,000, so a better format 
would have been to store a two-byte ushort rather than a 
10-byte float.  However the spec chose to have an encoded 
float there.


I would like to have a function of the form

public bool ubytes_to_double( ubytes[10] u, out double d ) 
{ /* stuff */ }


which would set d to the value encoded provided that the value 
is a number and is sane, and otherwise just return false.


So my plan is just to do this: examine the first 2 bytes to 
check the sign and see how big the number is, and if it is 
reasonable, convert the remaining 8 bytes to a fractional 
part, perhaps ignoring the last 2 or 3 as not being 
significant.


But --- it seems like this kind of task may be something that 
d already does, maybe with some constructor of a double or 
something.


Thanks in advance for any suggestions.

dan


On 32bit x86 an endianness swap and pointer cast to `real` 
should be enough.(seems to be the same format but i could be 
wrong.)
Else(afaik `real` on 64 bit x86 is just `double`?) you can 
always isolate sign mantissa and exponent to three isolated 
`double` values(cast from integer to `double`) and 
recalculate(`sign*mantissa*(2^^exponent)` according to 
wikipedia) the floating point number, since they mostly contain 
integers precision loss probably won't be a problem.


Thank you z.

My machine is 64-bit and is little-endian but the method you 
suggest actually gives the right answer in my case.


More exactly, a real on my machine is 16-bytes (128 bits), 
quadruple precision, and it has a sign bit with 15 bits of 
exponent.  But the 80-bit format also has a sign bit with 15 bits 
of exponent.


So all i have to do is declare a real y, cast &y it to ubyte*, 
and copy the 10 ubytes from the file over its first 10 bytes (but 
backwards).  Then the sign bit and exponent exactly match in 
position.  (The remaining 6 ubytes are left in their initial 
state because they're way out to the least significant part of 
the number.)


Now, for my final code, i'm not actually doing this because the 
size of real may be different on another machine, or the 
exponents may get different sizes due to a different layout, or 
some other problem.


So i just do it by hand (although i'm ignoring the last 4 ubytes 
since for my usage, ultimately it gets boiled down to a 32-bit 
integer anyway).  And "by hand" is pretty close to what you also 
mention in your mantissa*2^^exponent expression.


Thanks again.


Want a function that determines a double or float given its 80-bit IEEE 754 SANE (big endian) representation

2023-08-22 Thread dan via Digitalmars-d-learn

Hi,

I'm parsing some files, each containing (among other things) 10 
bytes said to represent an IEEE 754 extended floating point 
number, in SANE (Standard Apple Numerical Environment) form, as 
SANE existed in the early 1990s (so, big endian).


Note that the number actually stored will probably be a positive 
even integer less than 100,000, so a better format would have 
been to store a two-byte ushort rather than a 10-byte float.  
However the spec chose to have an encoded float there.


I would like to have a function of the form

public bool ubytes_to_double( ubytes[10] u, out double d ) { 
/* stuff */ }


which would set d to the value encoded provided that the value is 
a number and is sane, and otherwise just return false.


So my plan is just to do this: examine the first 2 bytes to check 
the sign and see how big the number is, and if it is reasonable, 
convert the remaining 8 bytes to a fractional part, perhaps 
ignoring the last 2 or 3 as not being significant.


But --- it seems like this kind of task may be something that d 
already does, maybe with some constructor of a double or 
something.


Thanks in advance for any suggestions.

dan


Re: Function which returns a sorted array without duplicates

2023-01-22 Thread dan via Digitalmars-d-learn

On Sunday, 22 January 2023 at 07:33:01 UTC, evilrat wrote:

On Sunday, 22 January 2023 at 04:42:09 UTC, dan wrote:
I would like to write a function which takes an array as 
input, and returns a sorted array without duplicates.



```d
private S[] _sort_array( S )( S[] x ) {
  import std.algorithm;
  auto y = x.dup;
  y.sort;
  auto z = y.uniq;
  // Cannot just return z; this gives:
  // Error: cannot implicitly convert expression `z` of 
type

  // `UniqResult!(binaryFun, uint[])` to `uint[]`


uniq and other algorithms often returns a lazy range, you can 
build an array by using `std.array.array()`


https://dlang.org/phobos/std_array.html#array

try something like this or just `return array(y.uniq);`

```d
private S[] _sort_array( S )( S[] x ) {
import std.algorithm;
import std.array;
return x.dup
   .sort
   .uniq
   .array();
}
```

And IIRC you probably don't need `dup` as sort produces a lazy 
range.


Thanks evilrat, this works perfectly, and is just the right style 
too (imvho).


So what i was missing was std.array.

Thanks also Ali for your subsequent clarifying remarks.

(Probably what i need to do is read a good book on the std 
library for d.)


dan

Thanks also Ali for your subsequent remarks


Function which returns a sorted array without duplicates

2023-01-21 Thread dan via Digitalmars-d-learn
I would like to write a function which takes an array as input, 
and returns a sorted array without duplicates.


In fact, i have a function which does this, but i think it may 
have some extra unnecessary steps.


```d
private S[] _sort_array( S )( S[] x ) {
  import std.algorithm;
  auto y = x.dup;
  y.sort;
  auto z = y.uniq;
  // Cannot just return z; this gives:
  // Error: cannot implicitly convert expression `z` of type
  // `UniqResult!(binaryFun, uint[])` to `uint[]`
  //
  // You also cannot just return cast( S[] ) z;
  //
  // Nor can you do:
  //  import std.conv;
  //  return to!( S[] )( z );
  typeof( x ) w;
  foreach ( v ; z ) w ~= v;
  return w;
}
```

My only constraint is that i really want to keep the same 
signature (i.e., return an array, not sharing structure or 
storage with the input).


Here's the usage:

```d
void main( ) {
  uint[] nums = [1, 3, 2, 5, 1, 4, 2, 8];
  auto sorted = _sort_array( nums );
  import std.stdio;
  writeln( "Input:  ", nums );
  writeln( "Output: ", sorted );
}
```

Thanks in advance for any info!

dan


Re: running a d compiler on the Mac Mini with an M1 chip

2021-03-26 Thread dan via Digitalmars-d-learn

On Friday, 26 March 2021 at 21:54:20 UTC, rikki cattermole wrote:

On 27/03/2021 10:51 AM, dan wrote:
Are there any d compilers that run natively on the Mac Mini 
with an M1 chip?


If so, does anybody here have any experience with them that 
can be shared?


If not, and your machine is a mac mini, how would you go about 
programming in d on it?


TIA for any info!


Looks like latest ldc has an arm build. But both dmd and ldc 
should already work due to x86 emulation that takes place.


https://github.com/ldc-developers/ldc/releases/tag/v1.25.1


Thanks Rikki!

If anybody has any particular experience using d on a mac mini 
with M1 that they want to share, please do post, but this does 
look promising.


dan


running a d compiler on the Mac Mini with an M1 chip

2021-03-26 Thread dan via Digitalmars-d-learn
Are there any d compilers that run natively on the Mac Mini with 
an M1 chip?


If so, does anybody here have any experience with them that can 
be shared?


If not, and your machine is a mac mini, how would you go about 
programming in d on it?


TIA for any info!


which free operating systems have a gtkd package?

2021-01-22 Thread dan via Digitalmars-d-learn
Debian 10 has a nice gtkd package, stored in libgtkd-3-dev i 
believe (when i installed it, i installed several packages at 
once, basically everything that had 'gtkd' as a substring in the 
package name).


It uses ldmd2 (part of the ldc package).

So it's possible to write and build a gtkd application using only 
debian packages.


I've done this with debian 10, and it works well imvho.

Although i have not tried it, it looks like ubuntu (20.4 and 
presumably later) also has a gtkd package.


I'm going to install a new os on a machine, and i'm trying to 
pick one that has a gtkd package available, so that all the d 
imports are in standard locations and i don't have to mess with 
anything.


So debian 10 and ubuntu 20.4 are candidates, but i'm wondering if 
there are others.  (I tried to find gtkd on linux mint but did 
not see a package for it, but man i could sure be wrong.)


Thanks in advance for any info!

dan


Re: Compile code for PowerNex OS

2020-09-06 Thread Dan Printzell via Digitalmars-d-learn

On Saturday, 5 September 2020 at 12:45:06 UTC, Quantium wrote:
I have a code that I need to compile for PowerNex OS, which 
compiler should I use and how to compile code for PowerNex?


Short version: You can't (right now).

Long version:
PowerNex is currently in broken development state so even if
you could compile code for it (which is not likely) you would
not be able to run it.

PowerNex uses a patched dmd version: 
https://github.com/PowerNex/PowerNex-dmd
and a patched binutils: 
https://github.com/PowerNex/PowerNex-binutils



Question:
What are you trying to compile?


Re: a function like writeln that returns a string rather than writes to a file

2020-05-02 Thread dan via Digitalmars-d-learn

On Saturday, 2 May 2020 at 10:36:47 UTC, Ali Çehreli wrote:
On 5/1/20 7:40 PM, dan wrote:> On Saturday, 2 May 2020 at 
02:29:43 UTC, H. S. Teoh wrote:

>> On Sat, May 02, 2020 at 02:22:42AM +, dan via
Digitalmars-d-learn
>> wrote:
>>> I'm looking for a function something like writeln or write,
but
>>> instead of writing to stdout, it writes to a string and
returns the
>>> string.
>> [...]
>>
>> import std.format : format;
>> string str = format("%s %s %s", obj1, obj2, obj3);
>>
>>
>> T
>
> Thanks HS!
>
> That looks like a good move, if format will do the string
conversion for
> me.
>
> But one thing that would be troublesome is that i would have
to make
> sure to count up the %s so that they match the number of
arguments.  I
> would like to do without that, just like writeln does.

If you can live with a mildly awkward way of passing it, 
format() can take the format string at compile time as well:


  string str = format!"%s %s %s"(obj1, obj2, obj3);

You get a compilation error if format specifications don't 
match the arguments. (There are bug reports about that check 
but it mostly works great.)


Ali


Thanks Ali.

That's also a good point, and would remove one of my qualms about 
all of the %s reps.


So if for any reason i cannot use the text function (or if i want 
to double check on the types of the objects) this would be a good 
thing to use.


dan


Re: a function like writeln that returns a string rather than writes to a file

2020-05-01 Thread dan via Digitalmars-d-learn
On Saturday, 2 May 2020 at 02:49:04 UTC, Steven Schveighoffer 
wrote:

On 5/1/20 10:40 PM, dan wrote:

On Saturday, 2 May 2020 at 02:29:43 UTC, H. S. Teoh wrote:
On Sat, May 02, 2020 at 02:22:42AM +, dan via 
Digitalmars-d-learn wrote:

[...]

[...]

import std.format : format;
string str = format("%s %s %s", obj1, obj2, obj3);


T


Thanks HS!

That looks like a good move, if format will do the string 
conversion for me.


But one thing that would be troublesome is that i would have 
to make sure to count up the %s so that they match the number 
of arguments.  I would like to do without that, just like 
writeln does.


import std.conv: text;

string str = text(obj1, " ", obj2, " ", obj3);

-Steve


Awesome, thanks Steve.  That's perfect.  So the function i was 
looking for was text (or, i guess, std.conv.text).


dan


Re: a function like writeln that returns a string rather than writes to a file

2020-05-01 Thread dan via Digitalmars-d-learn

On Saturday, 2 May 2020 at 02:29:43 UTC, H. S. Teoh wrote:
On Sat, May 02, 2020 at 02:22:42AM +, dan via 
Digitalmars-d-learn wrote:
I'm looking for a function something like writeln or write, 
but instead of writing to stdout, it writes to a string and 
returns the string.

[...]

import std.format : format;
string str = format("%s %s %s", obj1, obj2, obj3);


T


Thanks HS!

That looks like a good move, if format will do the string 
conversion for me.


But one thing that would be troublesome is that i would have to 
make sure to count up the %s so that they match the number of 
arguments.  I would like to do without that, just like writeln 
does.


Anyhow, though, thanks for point out format.

dan


a function like writeln that returns a string rather than writes to a file

2020-05-01 Thread dan via Digitalmars-d-learn
I'm looking for a function something like writeln or write, but 
instead of writing to stdout, it writes to a string and returns 
the string.


So i would like something like:

import std.stdio;
import std.conv;

string write_to_string(T...)(T values ) {
  string s;
  foreach ( value; values ) s ~= to!string( value );
  return s;
}

But because this is such a standard type of thing to do, i'd like 
to use whatever the standard function is for doing it, if there 
is one.


So . . . is there one?  Like maybe some way to dress a string up 
as a file and pass it through the usual write/writeln apparatus?  
My only real requirement is that it be something really easy to 
do.


Thanks in advance for any pointers.

dan


Re: There is Dlang Telegram Bot based on the official Telegram Bot API?

2020-04-05 Thread Dan Cirnat via Digitalmars-d-learn

On Friday, 3 April 2020 at 16:10:55 UTC, Baby Beaker wrote:
I create Bots for Telegram using Python or PHP. But I love 
Dlang and would like to create my Bots in Dlang. Is there any 
support for Dlang to create Telegram Bots?


Hi,

A quick search yielded this dub package: 
https://code.dlang.org/packages/tg-d


AFAIR the Telegram BOT API is HTTP and very simple. Should be 
straight forward to write your own client.
I found out some code I've written while playing with it a while 
ago: 
https://gist.github.com/cirnatdan/7d8cb26759f349579995c2703bbc1996


Have fun!


Re: Output predefined versions

2020-03-25 Thread Dan Cirnat via Digitalmars-d-learn

On Wednesday, 25 March 2020 at 17:35:07 UTC, kinke wrote:

Yes, just dummy-compile something with `-v` and check the line 
starting with `predefs`.


Exactly what I need, thank you!


Output predefined versions

2020-03-25 Thread Dan Cirnat via Digitalmars-d-learn

Hi,

I'm debugging issues with conditionally compiled code and I'd 
like to know exactly which versions are predefined by my compiler 
(Linux LDC Aarch64)


Is there a quick way to check which ones are predefined?

[0] https://dlang.org/spec/version.html#predefined-versions




Re: formatting a float or double in a string with all significant digits kept

2019-10-10 Thread dan via Digitalmars-d-learn

On Thursday, 10 October 2019 at 22:44:05 UTC, H. S. Teoh wrote:
On Thu, Oct 10, 2019 at 09:13:05PM +, Jon Degenhardt via 
Digitalmars-d-learn wrote:

On Thursday, 10 October 2019 at 17:12:25 UTC, dan wrote:
> Thanks also berni44 for the information about the dig 
> attribute, Jon
> for the neat packaging into one line using the attribute on 
> the

> type.
> Unfortunately, the version of gdc that comes with the 
> version of
> debian that i am using does not have the dig attribute yet, 
> but
> perhaps i can upgrade, and eventually i think gdc will have 
> it.


What's the output of dmd --version?  I find it extremely odd 
that .dig isn't supported.  AFAIK, it's been there since the 
early days of D. Certainly, it has been there since I started 
using D, which was before dmd was ever available in Debian.


What's the compiler output of:

pragma(msg, float.dig);

?


T


Thanks HS!

I sure thought i got a compile time error when i used .dig, but i 
tried

it again, and it works.

I tried the pragma, and it printed out 6, and i tried PI.dig and 
double.dig

and they're all working now.

Just for reference, i'm using what i think is the standard gdc on 
debian 9,

not dmd, and the version is 2068L.

Thanks again for your help in encouraging me to try harder, and 
thanks again

everybody else for all the help.

dan








Re: formatting a float or double in a string with all significant digits kept

2019-10-10 Thread dan via Digitalmars-d-learn

On Wednesday, 9 October 2019 at 10:54:49 UTC, David Briant wrote:

On Tuesday, 8 October 2019 at 20:37:03 UTC, dan wrote:
I have a double precision number that i would like to print 
all significant digits of, but no more than what are actually 
present in the number.  Or more exactly, i want to print the 
minimum number of digits necessary to recover the original 
number to within 2 or 3 least significant bits in the stored, 
in-core, version of its bit pattern.


For example,


import std.string;
import std.stdio;
import std.math;

void main( ) {
  auto t = format("%3.30f", PI );
  writeln("Value of PI is: ", PI, " or, : ", t);
}

The default way writeln prints is 5 digits to the right of the 
decimal point.


I can format to print with any number of digits, such as 30 
above, but that's too many.


For pi, the correct number of digits to print looks to be 
about 18 (and the extra 12 digits presumably are from the 
decimal expansion of the least significant bit?).


But i would like to be able to do this without knowing the 
expansion of pi, or writing too much code, especially if 
there's some d function like writeAllDigits or something 
similar.


Thanks in advance for any pointers!

dan


Hi Dan,

What's your usecase here, e.g. a csv/json reader / writer? You 
say it's for double precision numbers (64bit format) then 
provide an example for reals (80bit format). So I'm not certain 
your goal.


If you google "what every developer should know about doubles" 
you'll hit a number of useful articles that explain the common 
issues of floating point representation in detail.


-- David


Thanks David for your reply.

Thanks also berni44 for the information about the dig attribute,
Jon for the neat packaging into one line using the attribute on 
the type.
Unfortunately, the version of gdc that comes with the version of 
debian
that i am using does not have the dig attribute yet, but perhaps 
i can

upgrade, and eventually i think gdc will have it.

And thanks GreatSam4sure for your reply --- i searched the 
archives first,
but very poorly :(.  But it's easy to believe that i'm not the 
first person

in the history of the world with this issue.

Now, my use case is nothing so useful or general as a csv/json 
reader/writer.


I'm just doing some computations, incorrectly i think, and i want 
to be
able to print out the results and feed them to other software.  
I'm trying
to chase down a problem and rule out as many places for error as 
i can, and
it just seemed strange not to be able to get all the digits out 
in some easy way.
But the dig attribute seems to be a big step forward, and for 
that i am grateful.


dan


formatting a float or double in a string with all significant digits kept

2019-10-08 Thread dan via Digitalmars-d-learn
I have a double precision number that i would like to print all 
significant digits of, but no more than what are actually present 
in the number.  Or more exactly, i want to print the minimum 
number of digits necessary to recover the original number to 
within 2 or 3 least significant bits in the stored, in-core, 
version of its bit pattern.


For example,


import std.string;
import std.stdio;
import std.math;

void main( ) {
  auto t = format("%3.30f", PI );
  writeln("Value of PI is: ", PI, " or, : ", t);
}

The default way writeln prints is 5 digits to the right of the 
decimal point.


I can format to print with any number of digits, such as 30 
above, but that's too many.


For pi, the correct number of digits to print looks to be about 
18 (and the extra 12 digits presumably are from the decimal 
expansion of the least significant bit?).


But i would like to be able to do this without knowing the 
expansion of pi, or writing too much code, especially if there's 
some d function like writeAllDigits or something similar.


Thanks in advance for any pointers!

dan


Re: Small program producing binary with large filesize

2018-08-01 Thread Dan Barbarito via Digitalmars-d-learn

Thank you for all of the great answers, everyone!


Small program producing binary with large filesize

2018-07-31 Thread Dan Barbarito via Digitalmars-d-learn

Hi all,

I am starting to write a command line tool. So far it is a small 
(feature-wise) program but the file size is scaring me. It's 
already 13 megabytes, but I would expect it to be much smaller. 
Is it because I'm using 3 libraries so far? The libraries are: 
mir, vibe.d, and d2sqlite3. Would using these libraries be 
causing this file size?


The code can be found here 
(http://fossil.barbarito.me/finbot/zip/finbot.zip), if anyone 
wants to take a look. I am simply running "dub build" to build 
the binary. I tried running "dub build --build=release" but that 
didn't effect the file size too much.


Thanks!


GC in D and synadard library.

2017-12-21 Thread Dan Partelly via Digitalmars-d-learn


I started to look into D very recently. I would like to know the 
following, if you guys are so nice to help me:


1. What is the performance of D's GC, what trade-offs where done 
in design , and if a in-deep primer on efficient usage and 
gotchas of the current implementation exists.


2. GC is never good enough. What are the current plans in this 
area for D. In general, please point me to the place where 
current work on D is done.


3. I need to be able to run with GC totally disabled sometimes. 
In the light of this:
   - are there any features of core language which depend on 
garbage collection ? (i.e unbound arrays, strings ..)
   - are there any features from standard library which depend on 
active garbage collection?
   - Please point me to a list where there is an exhaustive 
enumeration of which language features *and* library features 
requires GC active. Looking at standard library docs I did not 
seen markings which identify clearly and unequivocally what 
requires GC active and what not.


4. Is Andrei Alexandrescu's book from 2009 on D still actual, or 
the language evolution made it obsolete ?


With thanks.



Re: How do i find a list of the methods Object implements, or maybe just locate the 'write' method?

2017-11-07 Thread dan via Digitalmars-d-learn

On Tuesday, 7 November 2017 at 21:32:26 UTC, Adam D. Ruppe wrote:

On Tuesday, 7 November 2017 at 21:25:00 UTC, dan wrote:

I looked in my distribution's object.d (debian stretch, gdc, in


Did you import std.stdio in the file?

If so, it is calling the std.stdio.write on the object (this is 
called UFCS, uniform function call syntax, the language allows 
you to call any free function in scope with obj.foo by 
rewriting it to foo(obj))


I then thought that i should just get an authoritative list of 
Object's methods, and hope something was documented there, but 
my searching for a list of for this also failed.


http://dpldocs.info/experimental-docs/object.Object.html


Awesome, great, thanks Adam!!!

I certainly was, and that must have been what was in play.

And thanks for the pointer to Object's methods (which are very 
few, as i thought).


dan


How do i find a list of the methods Object implements, or maybe just locate the 'write' method?

2017-11-07 Thread dan via Digitalmars-d-learn

I was writing some code and added a line like
 x.write;
expecting to fill it in later.

I forgot to actually write a function write, but it compiled 
anyway, and some testing shows that if you write

  auto o = new Object;
  o.write;
then this compiles just fine.  (The 'write' method, whatever it 
is, does not return a value, as 'auto y = o.write;' will not 
compile.)


So that presumably means that i'm about to override 'write' (when 
i finish up my class), but i have no idea what the original 
'write' does.


I looked in my distribution's object.d (debian stretch, gdc, in
/usr/lib/gcc/x86_64-linux-gnu/6/include/d/object.d) but i don't 
see anything that looks like a write method there.


I tried to do a net search, but 'write' is a very common word.

I then thought that i should just get an authoritative list of 
Object's methods, and hope something was documented there, but my 
searching for a list of for this also failed.


So i'd be grateful if somebody could tell me where i can find 
documentation on 'write' and/or what it means for an Object to 
write, and/or where i can see just what methods Object 
implements, and what those methods do.


Thanks in advance for any clues, or a pointer to page 1 of the 
manual if it's there and i'm just being dense.


dan


Re: using assignment statement as conditional in a where

2016-12-03 Thread dan via Digitalmars-d-learn
On Saturday, 3 December 2016 at 09:03:25 UTC, rikki cattermole 
wrote:

On 03/12/2016 9:55 PM, dan wrote:

[...]


If you can use another compiler do so, gdc is on an old 
frontend/Phobos now. I recommend ldc or you know the reference 
compiler dmd if performance/platform isn't an issue (not that 
dmd can't produce decent codegen).


This does compile:

int func() {
return 0;   
}

void main() {
int x;
while((x = func()) != 0) {

}
}


Thanks Rikki, that works great and is nearly ideal (doesn't seem 
to allow 'auto' but probably that's some scoping issue).


I do prefer gdc because it is gpl'ed, but appreciate any 
suggestions.


Thanks again for your help!

dan


using assignment statement as conditional in a where

2016-12-03 Thread dan via Digitalmars-d-learn

In c, you can have code like this:

static void wtest( void ) {
  int f;
  while ( ( f = some_val( ) ) ) {
printf(" our value is now: %d\n", f );
  }
}

gcc compiles this without warning or error (at least if you use 
the double parentheses to assure the compiler that you realize 
you are testing an assignment, not a comparison).


I would like to do the same thing in d, something like this:

private void wtest( ) {
  int f;
  while ( ( f = some_val( ) ) ) {
writeln(" our value is now: ", f );
  }
}

or even better:

private void wtest( ) {
  while ( ( auto f = some_val( ) ) ) {
writeln(" our value is now: ", f );
  }
}

This however does not work, and the gdc compiler says "assignment 
cannot be used as a condition, perhaps == was meant?"


I don't absolutely have to do it this way, as i guess i could do 
'while (true) {...' and then break if the assignment returns zero.


But i really, really would like to use the idiom of assigning a 
value from inside a while condition.


Is it possible to do this?  Perhaps with extra braces or 
something, like while ( {something here} ) {  } ?


TIA for any pointers or advice.

dan


Re: dependency analysis for makefile construction

2016-09-05 Thread dan via Digitalmars-d-learn

On Monday, 5 September 2016 at 18:49:25 UTC, Basile B. wrote:

On Monday, 5 September 2016 at 18:22:08 UTC, ag0aep6g wrote:

On 09/04/2016 12:07 AM, dan wrote:
Are there any FOSS tools for doing dependency analysis of 
[...]

[...]
I'm not aware of a standalone tool that does something like 
this. If you want to write one, you could do like rdmd and use 
`dmd -deps`/`dmd -v`, or you could use a standalone D parser 
like libdparse.


http://code.dlang.org/packages/libdparse


I have one in dastworx, based on dparse:

https://github.com/BBasile/Coedit/blob/master/dastworx/src/imports.d#L64



Thanks Basile and also ag0aep6g for your replies, which give me 
several things to try.


dan


dependency analysis for makefile construction

2016-09-03 Thread dan via Digitalmars-d-learn
Are there any FOSS tools for doing dependency analysis of (e.g.) 
all the d files in a directory, to let you know when a .o file 
needs to be regenerated?


This presumably would depend mostly on the import statements 
(including import of any file to be used in string construction, 
as in 'auto my_string = import("my_file");').


My guess is there must be, because one of the big deals about d 
is the more regular syntax it offers to make compiler building 
more reliable.


(I'm using gdc, and building with gnumake.)

TIA for any info!

dan


Re: Is there a d analog of strncmp?

2016-08-21 Thread dan via Digitalmars-d-learn

On Monday, 22 August 2016 at 01:45:02 UTC, Jonathan M Davis wrote:
On Monday, August 22, 2016 00:14:31 Adam D. Ruppe via 
Digitalmars-d-learn wrote:

int strncmp(string a, string b, int n) {
  if(a.length > n)
  a = a[0 .. n];
  if(b.length > n)
  b = b[0 .. n];
  import std.algorithm.comparison : cmp;
  return cmp(a, b);
}


Aside from the imports, it can be turned into a one-liner if 
you use take:


return cmp(take(a, n), take(b, n));

- Jonathan M Davis


Thanks Adam and Jonathan for your solutions.

For reference, one of the imports Jonathan is referring to is
   import std.range;

I did not know about take.  Well, i also did not know about cmp.  
So my code is probably not very idiomatic.  But i do appreciate 
all of you d-learn people!




Is there a d analog of strncmp?

2016-08-21 Thread dan via Digitalmars-d-learn
In c, there's this very nice function strncmp(s1,s2,count) which 
compares two c strings, using at most count characters.  count 
can be less than, more than, or equal to either or both of the 
lengths of the two strings.  It can be used to see if two 
c-strings have the same prefix of some length.


Now, strncmp indeed seems to be packaged up in core.stdc.string, 
but i would like to use some something like it on 2 d strings 
(which, as i understand it, need not be zero-terminated).


I suppose it would be possible to do some conversion with 
toStringz() or something and then invoke the strncmp(), but that 
seems very wordy and also it's not clear that it would handle all 
pairs of d strings (e.g., what if there were some 0's in the 
first count characters?).


So i would like to call a d function which works on d strings, 
but don't want to write my own if one already exists.  (At the 
very least, i'd have to get a much sharper understanding of d 
strings, whether internal 0's can occur, etc.  And i would not 
want to do egregious string allocation.)


TIA for any info!




Re: persistence, serialization, history (run-to-run) in small self-contained program

2016-07-14 Thread dan via Digitalmars-d-learn

On Thursday, 14 July 2016 at 08:28:56 UTC, Jacob Carlborg wrote:

On 2016-07-14 07:18, dan wrote:
I'm writing a small program (compiled with gdc on xubuntu 
16.04).


I would like it to remember a little data (a few kilobytes 
maybe).



.


My main concern is minimizing program complexity.


There's Orange [1]. It's a serialization library that 
serializes to XML.


[1] https://github.com/jacob-carlborg/orange


Thanks Jacob!

I was unaware of Orange.

@rikki --- Thanks also for your remarks.  Although in principle
both sql and json are complex, they are familiar, so if they
work as in other languages i'm hoping (knock on wood) they
won't seem complex.  As to what i'm storing, it's a little
indefinite now, but will include strings and times.



persistence, serialization, history (run-to-run) in small self-contained program

2016-07-13 Thread dan via Digitalmars-d-learn

I'm writing a small program (compiled with gdc on xubuntu 16.04).

I would like it to remember a little data (a few kilobytes maybe).

It looks like d comes with standard support for both sqlite3 and 
json --- is there any particular reason to prefer one over the 
other?   Or maybe something else entirely? (In each case, i would 
store the data in some file, and on second and subsequent runs of 
the program attempt to recover the data from that file if 
possible.)


My main concern is minimizing program complexity.

TIA for any advice.

dan



Re: standard alias for a class name inside the class code?

2016-05-28 Thread dan via Digitalmars-d-learn

On Sunday, 29 May 2016 at 02:44:33 UTC, jhps wrote:

On Sunday, 29 May 2016 at 00:48:20 UTC, dan wrote:

Especially in a declaration like
static typeof(this) make_instance( )
but also in the 'new typeof(this)'.  In both cases, 'this' 
doesn't even exist.



https://dlang.org/spec/declaration.html#Typeof

it's another 'this' that has not the same semantic as the 
reference holder.

Just like 'const' can have 3 meanings, 'this' also:

- this.member: typical usage, it hold the instance reference
- void foo(this T)(): template this parameter, T is 
typeof(this) where the template is used.
- typeof(this): you can use it in static func, this 'this' is 
not the 'this' instance.


OK, thanks JHPS for the detailed explanation of this construction 
Mithun pointed out, and also for the link.  It makes a lot of 
sense the way you put it.




Re: standard alias for a class name inside the class code?

2016-05-28 Thread dan via Digitalmars-d-learn

On Sunday, 29 May 2016 at 00:28:13 UTC, Mithun Hunsur wrote:

On Sunday, 29 May 2016 at 00:14:17 UTC, dan wrote:

Is there a standard alias for a class name inside class code?

Something like 'this' referring to a class instance, but 
referring instead to the class itself?


[...]


typeof(this) gets you the type of the current class. :)


Great!!

Thanks Mithun!

That certainly works.

But i sure don't understand how.

Especially in a declaration like
static typeof(this) make_instance( )
but also in the 'new typeof(this)'.  In both cases, 'this' 
doesn't even exist.


In fact, if you make a reference to this inside the static 
function make_instance(), you get an error:
'this' is only defined in non-static member functions, not 
make_instance


So the compiler itself states that 'this' is not defined.

But nevertheless, your method absolutely does work.

So i suppose i should not look a gift horse in the mouth, but i'm 
still puzzled.


Anyhow, thanks a million, because whether or not i understand 
your idiom, it is exactly what i need.


dan


standard alias for a class name inside the class code?

2016-05-28 Thread dan via Digitalmars-d-learn

Is there a standard alias for a class name inside class code?

Something like 'this' referring to a class instance, but 
referring instead to the class itself?


What i would like to do is have something like

class Clas {
   // alias Clas THIS; <- don't want this boilerplate
   static THIS make_instance(  ) {
   auto x = new THIS( );
   
   return x;
   }
}

This would be great for copy/paste, changing class names, and in 
general communicating your intention.


I'm guessing the answer is no, and that there's some compelling 
reason why a compiled language wouldn't want to provide this 
feature.  (But the php interpreter, whatever else is good or bad 
about it, does let you write 'new self(...)' and does the right 
thing with it.)


TIA for any clues.

dan


Re: Is there a way to make a class variable visible but constant to outsiders, but changeable (mutable) to the class itself?

2016-05-23 Thread dan via Digitalmars-d-learn

On Monday, 23 May 2016 at 07:03:08 UTC, chmike wrote:

On Saturday, 21 May 2016 at 17:32:47 UTC, dan wrote:

(This effect could be simulated by making my_var into a 
function, but i don't want to do that.)


May I ask why you don't want to do that ?

In D you can call a function without args without ().

So if you write

private int my_var_ = 4; // where 4 is the default 
initialization value

@property int my_var1() { return my_var_; }
final int my_var2() { return my_var_; }
int my_var3() { return my_var_; }

int x = obj.my_var1;
x = obj.my_var2;
x = obj.my_var3;


my_var3 is virtual so I guess you get the overhead of a virtual 
method call which is probably not what you want.


my_var2 can't be overriden and if it doesn't itself override a 
method with a same name in a base class the compiler may 
optimize its call by inlining it. It's like a static method 
with 'this' passed as argument.


I'm not fully sure about my_var1. I'm still a beginner, but I 
think the compiler will optimize it into inlined instruction if 
it can as for my_var2.


Making the user accessing the member variables directly may 
look like it's more efficient, but it's bad API design because 
you can't change the class implementation affecting my_var_ 
without breaking the API. The D way enforces good programming 
and API design and optimizes as much as possible.


Thanks Ch Mike for your reply and explanation, and the
further information about calling functions.

Thanks also to the other Mike, to Daniel for the interesting
union technique, and to Meta for further elaboration.
Daniel's union technique is pretty close to what i was
asking for.

Now, since you explicitly ask me 'why you don't
want to do that', i should answer.  But my answer
won't be nearly as good as your analysis and
explanation, nor as good as any of the other replies.  :(

Just aesthetically, i'd like to refer to the
variable within the class and outside the class
with exactly the same symbol.

But with all the ideas presented in the prior
discussion, i can get pretty close so it would
be a ridiculous point for me to complain about.

Thanks again for your help!

dan


Re: Is there a way to make a class variable visible but constant to outsiders, but changeable (mutable) to the class itself?

2016-05-21 Thread dan via Digitalmars-d-learn

Thanks Vit, Meta, and Yuxuan for your speedy help!

So 3 pieces to put together, function, const, and @property (and 
i guess final for protection against subclasses).




Is there a way to make a class variable visible but constant to outsiders, but changeable (mutable) to the class itself?

2016-05-21 Thread dan via Digitalmars-d-learn
Is it possible to have a class which has a variable which can be 
seen from the outside, but which can only be modified from the 
inside?


Something like:

class C {
  int my_var = 3; // semi_const??
  void do_something() { my_var = 4; }
}

And then in another file

auto c = new C();
c.my_var = 5; // <<<- should trigger a compile-time error
writeln("the value is ", c.my_var);  // <<<- should print 3
c.do_something();
writeln("the value is ", c.my_var);  // <<<- should print 4

Reading Alexandrescu's book suggests the answer is "no" (the only 
relevant type qualifiers are private, package, protected, public, 
and export, and none seem appropriate).


(This effect could be simulated by making my_var into a function, 
but i don't want to do that.)


TIA for any info!

dan






Re: Using D in Android App

2016-04-18 Thread Dan Olson via Digitalmars-d-learn
Justice  writes:

> On Saturday, 16 April 2016 at 04:04:24 UTC, Justice wrote:
>> Is it difficult to create a D business like app and connect it to
>> android through java for the interface?
>>
>> I'd rather create all the complex stuff in D and either use it
>> natively through java(I need a UI).
>>
>> If it is workable, can the same be said for IOS(just recompile the D
>> source to the IOS architecture then use it in an IOS app for the
>> ui)?
>
> Anyone?

Short answer is it should work: see "Alpha support for mobile" links on
http://dlang.org/download.html

Joakim has been pushing Android support and I've been working on getting
iOS into the core language.  The caveat is that both are alpha support
and it is hard to predict when they will be first class D citizens.

Speaking for the iOS support, the downloadable compiler is based on
2.068 (LDC 0.17.0) and will move to whatever LDC supports after 1.0.0 is
released.  I don't know of any problems at this stage, as long as you
just want to side load your app.  Submitting to the App Store is another
matter.  It has not been done yet and Apple's requirement to include
embedded bitcode is missing currently.
-- 
Dan


Re: GC configuration docs

2016-01-05 Thread Dan Olson via Digitalmars-d-learn
Rainer Schuetze  writes:

> On 05.01.2016 01:39, Dan Olson wrote:
>> I haven't played with any of the new GC configuration options introduced
>> in 2.067, but now need to.  An application on watchOS currently has
>> about 30 MB of RAM.  Is there any more documentation than the web page
>> https://dlang.org/spec/garbage.html or should I just browse druntime
>> code?
>
> I don't think there is more than that.
>
>>
>> Also pointers (pun maybe) on finding who has the references keeping
>> memory from
>> being collected.
>>
>
> There is a "leak detector" in the GC compiled into it the with
> -debug=LOGGING, but I guess noone has been using it the last couple of
> years (and it seems to me it doesn't really do anything more than
> printing allocations).
>
> I used -debug=PRINTF, -debug=PRINTF_COLLECT and -debug=PRINTF_TO_FILE
> in the past and grepped the resulting gcx.log. You might want to
> uncomment some printf in the mark function, too.

Thanks Raniner!


GC configuration docs

2016-01-04 Thread Dan Olson via Digitalmars-d-learn
I haven't played with any of the new GC configuration options introduced
in 2.067, but now need to.  An application on watchOS currently has
about 30 MB of RAM.  Is there any more documentation than the web page
https://dlang.org/spec/garbage.html or should I just browse druntime
code?

Also pointers (pun maybe) on finding who has the references keeping memory from
being collected.
-- 
Dan


Re: Looking for a language to hang my hat on.

2015-11-17 Thread Dan via Digitalmars-d-learn

Thanks everyone for taking the time to respond!

@Lobo,
Start using D now. It's not all or nothing so you don't have to 
give up on C++. I have several projects that contain both C++ 
and D intermixed.




Using both does seem like a good way to transition. I could 
combine the strengths of D with the strengths of c++. I have 
never mixed two programming languages in one project, all have 
contained one language exclusively. This is another bridge to 
cross.


D will make you a better C++ programmer, but especially C++ 
template programming. D metaprogramming is so easy to read, 
write and understand compared to C++ and many of the patterns 
still apply when you're standing knee deep in C++it.


I use c++ templates extensively, and if D offers a better 
solution that is fantastic.


@Chris Wright,


Your largest problem in the short term is documentation quality.


This concerns me since it makes it very difficult for people 
trying to learn the language. I don't need that additional 
frustration.



Your largest problem in the long run will be libraries.


Also concerning, but if I can combine the two languages somehow 
as lobo suggested, there may be a solution (just need to figure 
out how and how difficult that is).


...but you'd still have to write bindings. htod doesn't exactly 
work on Linux.


I am not exactly sure what that means, which is probably not a 
good sign.

---
@Russel Windmer
But doesn't code::blocks just interface with the compiler? I 
(naively?) thought I could just install the compiler and point 
code::blocks to that compiler.

---
@Bachmeier

What do you plan to do with D?


Good point, I did not make that clear. Right now I just want to 
use it for personal projects, but someday I hope to take it 
further.


Personally, I don't think there is a reason to transition. 
Instead, you should learn D and then use it when you are ready.


That is troubling, but reasons to transition must exist or the 
language would not exist, right? I find that if I "learn" a 
language I forget it unless I actually start using it, at least 
for a short while.


January 2016 is when I should have time to experiment with D. I 
will attempt to install the language in Linux and kick the tires 
for a while. If I continuously stumble into insurmountable 
barriers, the experiment will end.


Looking for a language to hang my hat on.

2015-11-16 Thread Dan via Digitalmars-d-learn
I am a very new c++ programmer, having just learned the language 
this year.


A few months ago I completed a course on Coursera that dealt with 
the security aspect of c (which I don't know, but it is similar 
enough):


https://class.coursera.org/softwaresec-008

The course highlighted just how dangerous c/c++ can be. My 
reaction to the course has been an increased use of shared/weak 
pointers over standard pointers, more judicious use of "assert" 
and increased use of destructors, where class pointers are 
destroyed via the destructor so I don't need to worry about 
memory leaks as much (all of my non-vector arrays are 
created/destroyed via a class w/ template).


Some of this slows programs down, but in reality it does not have 
much of an impact. But doubt will always linger that I caught 
every vulnerability. Therefore I am shopping for a language that 
codes like c++ but is safer.  It sounds like D may fit that 
requirement.


My platform of choice is 64-bit Fedora using Code::Blocks (yes, I 
use an IDE as a crutch). It seems that D supports this combo.


I have been lurking on this site over the past few weeks trying 
to decide when (and if) to make the transition. Can anyone here 
who has already made that transition tell me how smoothly it 
went? Any major unexpected problems? Advice?


thanks!
Dan


Re: Can't call GetWindowTextW - Error:undefined identifier

2015-06-17 Thread Dan via Digitalmars-d-learn

thank you so much John :)




Re: Can't call GetWindowTextW - Error:undefined identifier

2015-06-17 Thread Dan via Digitalmars-d-learn

thank you John it worked :)

do I always need do the same for all windows API?





Re: Can't call GetWindowTextW - Error:undefined identifier

2015-06-17 Thread Dan via Digitalmars-d-learn

GetWindowTextW(hWindow, buffer, sizeof(title)); <-- Problem here


please Ignore the sizeof(title) parameter, I copied that from c++ 
equivalent code :D




Re: Can't call GetWindowTextW - Error:undefined identifier

2015-06-17 Thread Dan via Digitalmars-d-learn

I'm new to Dlang and I have no Idea whats wrong with this code!

wchar[260] buffer;
HWND hWindow = GetForegroundWindow();
GetWindowTextW(hWindow, buffer, sizeof(title)); <-- Problem here


Can't call GetWindowTextW - Error:undefined identifier

2015-06-17 Thread Dan via Digitalmars-d-learn

hi

I'm using those imports:

import core.runtime;
import core.sys.windows.windows;

when I call GetWindowTextW DMD compiler complains! 
(error:undefined identifier)


any solution?


overloading evaluation (treating objects as functions)

2015-05-18 Thread dan via Digitalmars-d-learn

Is it possible to define a class F so that
auto f=new F();
writeln("The value of f at 7 is ",f(7));
compiles and works as expected?

So the idea would be to be able to use notation like
f(7)
instead of
f.eval(7)
or something along those lines.

My guess is no, it is impossible to do this, because i can't find 
it on the internet or in Alexandrescu's book.


But it is also possible that everybody considers it so obvious 
that they just don't elaborate on it.  I'd be delighted if there 
were the case, at least if somebody would elaborate on it if so.


TIA for any info!

dan


Re: overloading evaluation (treating objects as functions)

2015-05-18 Thread dan via Digitalmars-d-learn

Awesome!!

Thanks Gary and namespace (and obviously i gotta improve my 
google-fu).


dan

On Sunday, 17 May 2015 at 19:40:10 UTC, Gary Willoughby wrote:

On Sunday, 17 May 2015 at 18:58:32 UTC, Namespace wrote:

http://dlang.org/operatoroverloading.html#function-call


Like this:

module main;

import std.stdio;

class F
{
int opCall(int value)
{
return value * 2;
}
}

void main(string[] args)
{
auto f = new F();

writeln("The value of f at 7 is ", f(7));
}




Re: Is this expected? default to public members in private class

2015-05-04 Thread Dan Olson via Digitalmars-d-learn
ketmar  writes:

> On Sun, 03 May 2015 18:07:20 -0700, Dan Olson wrote:
>
>> It seems a private class or struct defaults to public members.  Just
>> curious if this is intended.  I would have expected private all the way
>> down unless overriden.
>
> i bet it is intended. protection of struct/class members is independed of 
> protection of struct/class itself. this is good for code consistency: no 
> changing of outer protection flags can alter struct/class inner 
> machinery. so if you changed your mind about protection level of some 
> global things, you shouldn't unnecessary "fix" your code in completely 
> unrelated places.

Thanks ketmar, that makes sense.  I am in midst of adding an option to
have dscanner skip private/package declarations when emitting etags (new
--etags option) and I want to match what the D lang spec would say is
private (if it did say).  For now I have to reverse engineer based on
compiler and forums, but don't want to mimic a compiler bug.


Is this expected? default to public members in private class

2015-05-03 Thread Dan Olson via Digitalmars-d-learn
It seems a private class or struct defaults to public members.  Just
curious if this is intended.  I would have expected private all the way
down unless overriden.

--- plugh.d
module plugh;
auto makeFoo() {return new Foo;}

private:

class Foo
{
void maybepriv() {}
private void priv() {}
public void pub() {}
}

--- xyzzy.d
module xyzzy;
import plugh;

void main()
{
auto f = makeFoo();
f.maybepriv();  // is accessible after all
//f.priv(); // err expected, member private
f.pub();
}

--
Dan Olson


Re: std.json questions

2015-04-25 Thread Dan Olson via Digitalmars-d-learn
"tired_eyes"  writes:
>
> First issue: what is the proper ("idiomatic") way to conver JSONValue
> to the proper types?
>
> Second: what is the proper way of handling boolean values in JSON (how
> to convert JSON_TYPE.TRUE and JSON_TYPE.FALSE to bool)?
>
> Righ now I'm doing is something like this:
>
> string data = readText("file.json");
> JSONValue[string] parsedData = parseJSON(data).object;
> JSONValue[] etities = stateData["entities"].array;
>
> foreach(e; entities) {
> int x = to!int(e["x"].integer);
> int y = to!int(e["y"].integer);
> string texture = stripExtension(e["texture"].str);
>
> auto isControllable = "isControllable" in e;
>
> if (isControllable !is null) {
> if (e["isControllable"].type == JSON_TYPE.TRUE) {
> isControllable = true;
> } else {
> isControllable = false;
> }
> }
> }
>
> I think this is ugly and clunky approach, what is the beautiful one?
>
> A brief look at code.dlang.org gives us 7 (!) additional JSON
> libraries. Keeping in mind that D community isn't so huge, I think I'm
> not the only person struggling with std.json. Are there any plans on
> upgrading it?

Hi and welcome to D land.  I see discussions on how std.json needs to be
upgraded.  And it is not well documented.

I tried to progressively simplify the code that was posted to show what
can be done, but keeping the same spirit.  Not necessarily beautiful,
but less verbose code. I did not see a simpler way to deal with bools in
the std.json code.  Others here are experts on idiomatic D, they may
show something much better.

// First , make it work and show all types
void f1()
{
string data = readText("file.json");
JSONValue parsedData = parseJSON(data);
JSONValue entities = parsedData["entities"];

foreach(size_t index, e; entities) {
long x = e["x"].integer;
long y = e["y"].integer;
string texture = stripExtension(e["texture"].str);

bool isControllable = false;

if ("isControllable" in e) {
if (e["isControllable"].type == JSON_TYPE.TRUE) {
isControllable = true;
} else {
isControllable = false;
}
}
writefln("x %d y %d texture %s isControllable %s",
 x, y, texture, isControllable);
}
}

// Next,  let compiler figure types for us
void f2()
{
auto data = readText("file.json");
auto parsedData = parseJSON(data);
auto entities = parsedData["entities"];

foreach(size_t _, e; entities) {
auto x = e["x"].integer;
auto y = e["y"].integer;
auto texture = stripExtension(e["texture"].str);

bool isControllable = false;

if ("isControllable" in e) {
isControllable = e["isControllable"].type == JSON_TYPE.TRUE;
}
writefln("x %d y %d texture %s isControllable %s",
 x, y, texture, isControllable);
}
}

// A little simpler isControllable.
void f3()
{
auto parsedData = readText("file.json").parseJSON;

foreach(size_t _, e; parsedData["entities"]) {
auto x = e["x"].integer;
auto y = e["y"].integer;
auto texture = stripExtension(e["texture"].str);
auto isControllable = "isControllable" in e &&
   e["isControllable"].type == JSON_TYPE.TRUE;
writefln("x %d y %d texture %s isControllable %s",
 x, y, texture, isControllable);
}
}



Re: Weird OSX issue

2015-04-25 Thread Dan Olson via Digitalmars-d-learn
Jacob Carlborg  writes:

> On 2015-04-24 20:37, Steven Schveighoffer wrote:
>
>> So am I going crazy? Or is dmd doing things differently depending on
>> where its environment is? Any compiler gurus out there understand why
>> the symbol is different?
>>
>> I don't want to file a bug with this, because it seems dependent on
>> installation location, would possibly not be reproducible.
>
> I can't reproduce this with DMD from DVM (compiler is installed in the
> user home directory).

I have lots of version laying around and they all worked fine on the
posted code.

But maybe a clue here...

$ ~/dmd2.066.0/osx/bin/dmd mod1.d
$ nm mod1.o | grep start
 U _D4core6thread6Thread5startMFZv
$ dmd mod1.d
$ nm mod1.o | grep start
 U _D4core6thread6Thread5startMFNbZC4core6thread6Thread

--- a/src/core/thread.d
+++ b/src/core/thread.d
@@ -587,7 +587,7 @@ class Thread
  * Throws:
  *  ThreadException if the thread fails to start.
  */
-final Thread start()
+final Thread start() nothrow
 in
 {
 assert( !next && !prev );

I wonder if dmd -v will show where its picking up stuff.


Re: extern(C++) linker errors

2015-04-21 Thread Dan Olson via Digitalmars-d-learn
bitwise  writes:
> I am trying to interface to C++, and getting linker errors. Below are
> my 3 source files and 2 build scripts with their associated
> errors. Can anyone see what I'm doing wrong?

Hi, I think both examples need libstdc++ added when you link
(-L-lstdc++).  That should resolve the missing C++ operators.

For script1.sh with ldc2 I see an extra underscore in C++ mangled names.
You must be on OS X.  ldc was just fixed in merge-2.067 branch to remove
an extra underscore on OS X.  If you want to experiment, you can build
https://github.com/ldc-developers/ldc/tree/merge-2.067 and check it out.
There are still a few tests to reolve, but it works pretty well for me.
--
Dan


Re: Unittest in a windows app

2014-12-20 Thread Dan Nestor via Digitalmars-d-learn
I managed to isolate the problem to the following. Program 1 
below works (displays unit test failure when run), while program 
2 does not.


* Program 1 *

import std.stdio;

unittest
{
assert(false);
}

void main()
{
writeln("Hello D-World!");
}

* Program 2 *

module winmain;

import core.sys.windows.windows;

unittest {
assert(false);
}

extern (Windows)
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR
lpCmdLine, int nCmdShow)
{
return 0;
}


Unittest in a windows app

2014-12-19 Thread Dan Nestor via Digitalmars-d-learn

Hello everybody, this is my first post on this forum.

I have a question about unit testing a Windows application. I
have slightly modified Visual D's default Windows application
stub to the following:


module winmain;

import core.runtime;
import core.sys.windows.windows;

unittest {
assert(false);
}

extern (Windows)
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR
lpCmdLine, int nCmdShow)
{
int result;

void exceptionHandler(Throwable e)
{
throw e;
}

try
{
Runtime.initialize();
result = myWinMain(hInstance, hPrevInstance, lpCmdLine,
nCmdShow);
Runtime.terminate();
}
catch (Throwable o) // catch any uncaught exceptions
{
MessageBoxA(null, cast(char *)o.toString(), "Error", MB_OK |
MB_ICONEXCLAMATION);
result = 0; // failed
}

return result;
}

int myWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR
lpCmdLine, int nCmdShow)
{
/* ... insert user code here ... */
throw new Exception("not implemented");
return 0;
}


I compiled it with the `-unittest` option. Strangely, when
running the app, no error is displayed, and the application
proceeds as usual. I would expect the program to display the unit
test failure and stop (the behaviour I have observed for console
applications). What am I missing?

Thanks for helping!

Dan


Re: Are there any methods like isDestroyed or isDisposed to detect whether some object is destroyed or not?

2014-12-14 Thread Dan Olson via Digitalmars-d-learn
"Marc "Schütz\""  writes:

> On Saturday, 13 December 2014 at 21:20:43 UTC, Andrey Derzhavin wrote:
>>>
>>> import std.stdio;
>>>
>>> class ObjectAType {
>>>bool ok;
>>>this() {ok = true;}
>>> }
>>>
>>> void main()
>>> {
>>>auto a = new ObjectAType;
>>>assert(a.ok);
>>>destroy(a);
>>>assert(!a.ok);  // a has been destroyed.
>>> }
>>>
>>
>> This method of detection of collected objects is what I needed.
>> Thanks to everybody for your advise.
>
> Be careful - the memory could still have been reused. For example:
>
> assert(a.ok);
> destroy(a);
> // ... lots of code, maybe multi-threaded ...
> assert(!a.ok);// can fail
>
> If between `destroy()` and the second `assert()`, the memory of the
> object is collected, a new object (of the same or different type) can
> have been placed there. You will then read an arbitrary piece of data
> from that new object, which may or may not evaluate to `true`.

In this case the object cannot be collected by gc because there is still
a good reference to it (variable 'a').  I agree if delete was used
instead of destroy that is would be unsafe.
--
dano


Re: Are there any methods like isDestroyed or isDisposed to detect whether some object is destroyed or not?

2014-12-13 Thread Dan Olson via Digitalmars-d-learn
"Andrey Derzhavin"  writes:

> Hello!
>
> We have object, for example, objA.
>
> ObjectAType objA = new ObjectAType(...);
>
> // we have a many references to objA
>
> void someFunction1(...)
> {
>// destroying the objA
>destroy(one_of_the_refToObjA);
>
>//
> }
>
>
> void someFunction2()
> {
>// "segmentation fault" if the objA is destroyed
>another_refToObjA.method1();
>
>// I need a safe way (without using signals) to detect whether
> object
>// destroyed or not, like this
>// if (!isDestroyed(another_refToObjA))
>//   another_refToObjA.method1();
>
> }
>
> // call functions
> someFunction1(..);
>
> // . some other operations...
>
> // the objectA (objA) is destroyed, but debugger shows us a not null
> reference
> // to that objA. However, when we try to call some methods of objectA
> or
> // try to use it's variables we get a "segmentation fault" error (in
> // someFunction2, when objA is destroyed).
> someFunction2(...);
>
> Thanks.

Maybe this would work for you.  If you own your ObjectAType class, you
could add an ok flag.  destroy() sets all members to .init value and
TDPL says this will be the case (lookup "clear" which was renamed
"destroy").

import std.stdio;

class ObjectAType {
bool ok;
this() {ok = true;}
}

void main()
{
auto a = new ObjectAType;
assert(a.ok);
destroy(a);
assert(!a.ok);  // a has been destroyed.
}

--
dano


Re: mixin template had error by calling shared function

2014-12-11 Thread Dan Olson via Digitalmars-d-learn
Here is a way that will work.

"Vlasov Roman"  writes:
> I have this code
>
> mixin template Template(void function() func1, void function() func2)

mixin template Template(alias func1, alias func2)

> class SomeClass {
>   mixin Template!(&func, &func23);

mixin Template!(func, func23);

--
dano


Re: std.parallelism: How to wait all tasks finished?

2014-02-03 Thread Dan Killebrew
It seems to me that worker threads will continue as long as 
the queue isn't empty. So if a task adds another task to the 
pool, some worker will process the newly enqueued task.


No. After taskPool.finish() no way to add new tasks to the 
queue. taskPool.put will not add new tasks.


Then perhaps you need to create a new TaskPool (and make sure 
that workers add their tasks to the correct task pool), so that 
you can wait on the first task pool, then wait on the second task 
pool, etc.


auto phase1 = new TaskPool();
//make sure all new tasks are added to phase1
phase1.finish(true);

auto phase2 = new TaskPool();
//make sure all new tasks are added to phase2
phase2.finish(true);


Re: std.parallelism: How to wait all tasks finished?

2014-02-02 Thread Dan Killebrew
  // Next line will block execution until all tasks already in 
queue finished.

  // Almost all what I need, but new tasks will not be started.
  taskPool.finish(true);
}


Are you sure TaskPool.finish isn't what you're looking for?

"Signals worker threads to terminate when the queue becomes 
empty."


It seems to me that worker threads will continue as long as the 
queue isn't empty. So if a task adds another task to the pool, 
some worker will process the newly enqueued task.


Re: mixin template

2014-01-30 Thread Dan Killebrew

On Friday, 31 January 2014 at 06:24:27 UTC, Dan Killebrew wrote:

mixin template Foo(alias a){ alias Foo=a; }
pragma(msg, Foo!2); // error

template Bar(alias a){ alias Bar=a; }
pragma(msg, Bar!2); // ok


As far as I can tell, 'mixin template' does nothing new;


(besides fail to compile in Timon's reply). I should have said 
"it does nothing helpful."


Re: mixin template

2014-01-30 Thread Dan Killebrew

mixin template Foo(alias a){ alias Foo=a; }
pragma(msg, Foo!2); // error

template Bar(alias a){ alias Bar=a; }
pragma(msg, Bar!2); // ok


Perhaps I was unclear. What I meant:
What does 'mixin template' do that 'template' does not?
Where would I use 'mixin template'?

As far as I can tell, 'mixin template' does nothing new; 
'template' is sufficient. Thus, 'mixin template' seems like 
pointless extra syntax.


As I said before, this page http://dlang.org/template-mixin.html 
could have replaced all instances of 'mixin template' with 
'template' and it would compile (I tested all examples) and run 
the same (perhaps not true? I tested about half).


Even the example in TDPL on page 284 works the same when I 
replace 'mixin template' with 'template': (this is my slightly 
modified version) http://dpaste.dzfl.pl/b582c899fc3f


Re: mixin template

2014-01-27 Thread Dan Killebrew
Found this: 
http://forum.dlang.org/thread/ntuysfcivhbphnhnn...@forum.dlang.org#post-mailman.1409.1339356130.24740.digitalmars-d-learn:40puremagic.com


If what Jonathan says is true, then 
http://dlang.org/template-mixin.html should be updated: s/mixin 
template/template/


Re: std.json tree navigation help

2014-01-27 Thread Dan Killebrew
Check out the json module in vibe.d. Maybe copy it into your own 
application (since it can't be used as a library, yet).

http://vibed.org/api/vibe.data.json/
https://github.com/rejectedsoftware/vibe.d


mixin template

2014-01-27 Thread Dan Killebrew

What is the difference between:
A
---
template Foo() {
  int x = 5;
}

B
-
mixin template Foo() {
  int x = 5;
}

The full example is from the first code sample on 
http://dlang.org/template-mixin.html  Both A and B compile and 
when run, have the exact same output. So how is 'mixin template' 
different from 'template'?


Full example, slightly modified to actually run:
import std.stdio;

 template Foo() {
//mixin template Foo() {
  int x = 5;
}

mixin Foo;

struct Bar {
  mixin Foo;
}

void main() {
  writefln("x = %d", x);  // prints 5
  {
Bar b;
int x = 3;

writefln("b.x = %d", b.x); // prints 5
writefln("x = %d", x); // prints 3
{
  mixin Foo;
  writefln("x = %d", x);   // prints 5
  x = 4;
  writefln("x = %d", x);   // prints 4
}
writefln("x = %d", x); // prints 3
  }
  writefln("x = %d", x);   // prints 5
}


Re: Idiomatic way to share mutable data?

2013-12-23 Thread Dan Killebrew
On Sunday, 22 December 2013 at 21:07:11 UTC, Charles McAnany 
wrote:

Friends,
I'm writing a little molecular simulator. Without boring you 
with the details, here's the gist of it:


struct Atom{
double x, vx;
double interaction(Atom a2){
return (a2.x-this.x)^^2; //more complicated in reality
}
}

main(){
Atom[] atoms = (a bunch of atoms in random positions);
foreach(timestep; 1..1000){ //L0
foreach(atom; atoms){ //L1
foreach(partner; atoms){ //L2
atom.vx += atom.interaction(partner)/mass; 
//F=ma

}
}
foreach(atom; atoms){ //L3
atom.x += atom.vx * deltaT;
}
}
}

So here's the conundrum: How do I parallelize this efficiently? 
The first loop, L0, is not parallelizable at all, and I think 
the best speedup will be in parallelizing L1. But I immediately 
run into trouble: all the threads need access to all of atoms, 
and every atom's position is changed on every pass through L0. 
So to do this purely with message passing would involve copying 
the entirety of atoms to every thread every L0 pass. Clearly, 
shared state is desirable.


But I don't need to be careful about the shared state at all; 
L1 only reads Atom.x, and only writes Atom.vx. L3 only reads 
Atom.vx and only writes Atom.x There's no data dependency at 
all inside L1 and L3.


Is there a way to inform the compiler of this without just 
aggressively casting things to shared and immutable?


On that note, how do you pass a reference to a thread (via 
send) without the compiler yelling at you? Do you 
cast(immutable Atom[]) on send and cast(Atom[]) on receive?



If you're doing a range limited interaction, partition the atoms 
spatially and have each core handle a fixed 3D volume. Check out 
the NT method 
http://www.cs.cmu.edu/afs/cs/academic/class/15869-f11/www/readings/shaw05_ntmethod.pdf 
  When the core that owns an atom detects that it may be in 
interaction range for atom(s) owned by another core, send updates 
to that other core.


Re: sending an Exception and print it

2013-12-21 Thread Dan Killebrew
I just wanted to add that the "can't format immutable Exception" 
also prevents me from doing this:

  auto exception = receiveOnly!(immutable Exception)();
because receiveOnly creates a tuple which implements a toString 
that uses indirectly uses formatObject. So I'm forced to use the 
slightly more clunky recieve() as seen on DPaste.


sending an Exception and print it

2013-12-21 Thread Dan Killebrew

I'm sending an exception from a worker thread to the owner thread
to be logged/printed. Using DMD64 D Compiler v2.064

http://dpaste.dzfl.pl/7c8b68bd

Using std.concurrency prevents me from passing a naked Exception.
So the owner receives either a shared or immutable Exception.
I can't format a shared Exception:
/usr/include/dmd/phobos/std/format.d(2602): Error: static assert
"unable to format shared objects"
I can't format an immutable Exception:
/usr/include/dmd/phobos/std/format.d(2610): Error: template
instance formatObject!(Appender!string, immutable(Exception),
char) does not match template declaration formatObject(Writer, T,
Char)(ref Writer w, ref T val, ref FormatSpec!Char f) if
(hasToString!(T, Char))


What gives? I expected the immutable Exception to be formattable.

My current workaround is to cast to const Exception. Is there
something else I should be doing here?


Re: Tricky code with exceptions

2013-05-09 Thread Dan Olson
"evilrat"  writes:

> On Thursday, 9 May 2013 at 20:33:17 UTC, bearophile wrote:
>> Brad Anderson:
>>
>>> a 64-bit Windows dmd build did not crash and here is the output.
>>
>> Thank you for the data point. So maybe the problem is only on 32 bit
>> Windows.
>>
>> Bye,
>> bearophile
>
> win8 dmd 2.062 32-bit also crashes

Anybody looked at the assembly for the crashing executables?  The truth
is in there.

 


Re: debugging on Mac OSX

2013-04-29 Thread Dan

On Monday, 29 April 2013 at 16:48:27 UTC, Jacob Carlborg wrote:

On 2013-04-29 14:45, Daniel Davidson wrote:
Ho do you debug D executables on mac os x in which debug 
symbols are
available (preferably a setup that works in emacs with gdb or 
gud-gdb)?


This thread seems to bring up the issue I am seeing:

http://forum.dlang.org/thread/k55tiv$28u3$1...@digitalmars.com

but no solution is provided. Also, this bug,

http://d.puremagic.com/issues/show_bug.cgi?id=2741

seems to specifically talk to the issue and is closed RESOLVED 
FIXED.

Yet I am unable to get it to work.

In this thread on usability of D dev environment from OSX, 
several
people are having success developing D on OSX. Question is, do 
they

debug and if so how? (hopefully not just print statements)

I am a switcher, just trying out the mac ecosystem. On ubuntu 
linux, for
my rather small sample apps emacs (M-x gdb) just works, 
assuming I've
built with rdmd specifying debug and that the command build 
only (to

keep the binary). The symbols and line numbers are available.

Is there a setup for Mac that others are having success with?


See:

* http://d.puremagic.com/issues/show_bug.cgi?id=8172
* http://d.puremagic.com/issues/show_bug.cgi?id=8207


Thanks. What is the takeaway? That it does not work and can not 
work until these two bugs are fixed? A simple "I don't think you 
can get there from here"?


Re: Orange lib help

2013-03-27 Thread Dan

On Tuesday, 26 March 2013 at 19:35:51 UTC, Jacob Carlborg wrote:


I'll take a look. Which compiler and version are you using?



DMD64 D Compiler v2.062
ubuntu 64 bit

thanks!


Orange lib help

2013-03-26 Thread Dan

Hi -

I get some errors from this simple code:

class Class_a {
   double[2][2] ob;
}
class Class_b : Class_a { int obb;}
Serializer.register!(Class_b);

The error is:
Error: variable 
orange.serialization.Serializer.Serializer.serializeArray!(inout(double[2LU][2LU])).serializeArray.__lambda2008.__aggr2839 
inout variables can only be declared inside inout functions


I can't seem to find any answers in the documentation. Anybody 
could help me out?


thanks
dan


static functions associated with enums

2013-03-21 Thread Dan

I have an enum, say:

enum AssetCategory {
  Investment,
  PrimaryResidence,
  FamilyProperty,
  FinancialInstrument
}

and I have functions that convert to/from strings to be used in 
Json (via vibe json). The vibe wants to call out to user supplied 
toJson/fromJson if both functions are provided and the test for 
it is:


Json serializeToJson(T)(T value) {
...
 static if( __traits(compiles, value = 
T.fromJson(value.toJson())) ){

   return value.toJson();
...
}

I would like to use this feature to have the json output the 
string instead of numeric value (while still retaining numeric 
value in data structures). The toJson/fromJson functions below 
are close. They allow for this:


if( __traits(compiles, t.fromJson(t.toJson()) ))

to be true - but that is not the same thing. Is there a trickery 
to associate a static function with an enum? (e.g. 
AssetCategory.fromJson(json)) )


Thanks
Dan
---

static void fromJson(ref AssetCategory assetType, Json src) {
  string value = cast(string)src;
  writeln("value is ",value);
  final switch(value) {
  case "Investment": { assetType = AssetCategory.Investment; 
break; }
  case "PrimaryResidence": { assetType = 
AssetCategory.PrimaryResidence; break; }
  case "FamilyProperty": { assetType = 
AssetCategory.FamilyProperty; break; }
  case "FinancialInstrument": { assetType = 
AssetCategory.FinancialInstrument; break; }

  }
}

static Json toJson(AssetCategory assetType) {
  auto result = Json();
  result = text(assetType);
  return result;
}


Re: looking for V[string] workarounds

2013-03-20 Thread Dan

On Wednesday, 20 March 2013 at 17:44:16 UTC, Ali Çehreli wrote:
In that case, brute force to the rescue (nc stands for 
non-const): :)


  this(const(Series[string]) source) {
  auto nc_source = cast(Series[string])source;
itemToSeries = nc_source.dup;
  }



Wow - that worked. Thanks! I hope it is safe.



Re: initializing const maps with value types having aliasing

2013-03-20 Thread Dan
On Wednesday, 20 March 2013 at 19:01:27 UTC, Jonathan M Davis 
wrote:
Why are you casting? The cast shouldn't be necessary, because 
you're doing the

initialization inside a static constructor.


Without it I get:
Error: mutable method cmap.S.__postblit is not callable using a 
const object

Error: cannot modify struct this Slot with immutable members



If you had problems, I'd expect it
to be that AAs don't work properly when const (I know that 
there are issues
when they're immutable) or that you can't insert elements into 
a const or
immutable AA (which you'll never be able to do). But what 
you're doing here
should work just fine without the cast. Assuming that AAs 
worked with const or
immutable correctly, then it would be normal to do something 
like


immutable int[string] aa;

static this()
{
 int[string] temp;
 temp["foo"] = 7;
 temp["blah"] = 12;
 aa = assumeUnique(temp);
}


For now it seems the cast is necessary - so as long as it is safe.

I am not using 'immutable S[string]aa', but it would be 
interesting to see how that could be initialized. So, how to 
initialize aa. Does assumeUnique work for associative arrays?

--
import std.exception;

struct S {
  this(this) { x = x.dup; }
  char[] x;
}

immutable S[string] aa;

static this() {
   // now what
}

Thakns
Dan


initializing const maps with value types having aliasing

2013-03-20 Thread Dan
The following works and is the only way I have found to 
initialize m.

Unfortunately it requires the cast.

Is this safe to do?
Is there a better way?
Is this a bug or are future features coming to clean it up?

Thanks
Dan

--
import std.stdio;
struct S {
  this(this) { x = x.dup; }
  char[] x;
}

const(S[string]) m;
static this() {
  // Is there a cleaner way?
  cast(S[string])m = [ "foo" : S(['a']) ];
}

void main() {
  writeln(m["foo"]);
}


Re: looking for V[string] workarounds

2013-03-20 Thread Dan

On Wednesday, 20 March 2013 at 17:11:02 UTC, Ali Çehreli wrote:
The code compiles with 2.062 and an earlier version of 2.063 if 
you accept letting go of const-correctness there:


this(Series[string] source) {



Thanks Ali. But, removing const there then requires non-const 
instances to be passed in, due to const transitivity. So that 
requirement would ripple a change to all already const correct 
instances to now need to flip to non-const. I'm looking for a 
const correct solution. It should be doable ... I just have had 
no luck with it.


Thanks
Dan



looking for V[string] workarounds

2013-03-20 Thread Dan
Can the following be made to build and run, but keep the intent 
of what is shown. I realize it touches on several bugs related to 
const, postblit, and map - but I'm having trouble finding the 
magic combination. The idea is simply have assets store multiple 
series of data in a map indexed by the asset name.


Thanks,
Dan

import std.stdio;
struct Series {
  // REQUIRED - need to have no aliasing
  this(this) { data = data.dup;  }
  private double[] data;
}

struct Assets {
  this(this) { itemToSeries.dup; }
  // REQUIRED - want ctor to dup arg to ensure no aliasing
  this(const(Series[string]) source) {
itemToSeries = source.dup;
  }
  private Series[string] itemToSeries;
}

void main() {
  auto data = [ "house" : Series([1,2,3.0])];
  auto assets = Assets(data);
  writeln(assets);
}


Re: recursive equal, and firstDifference functions

2013-03-20 Thread Dan
On Wednesday, 20 March 2013 at 03:10:41 UTC, Jonathan M Davis 
wrote:


The way == is defined is very clean and straightforward. There 
_are_ bugs which
complicate things (e.g. 
http://d.puremagic.com/issues/show_bug.cgi?id=3789 ),

but those can and will be fixed. The design itself is solid.



Thanks for the detailed explanation. If 3789 covers strings, 
dynamic arrays and associative arrays and it were fixed then I 
agree, it is clean and straightforward. If I read it correctly 
with this fix it would change the current opEquals from 
semantically shallow to semantically deep by default. 
Semantically deep equality is comfortable to me, but I would 
imagine by now there is a fair amount of code that might rely on 
a false result from opEquals if the members (slices, associative 
arrays) are not bitwise the same.


Thanks
Dan



Re: recursive equal, and firstDifference functions

2013-03-19 Thread Dan
On Wednesday, 20 March 2013 at 02:54:23 UTC, Jonathan M Davis 
wrote:

On Wednesday, March 20, 2013 03:48:38 Dan wrote:

On Wednesday, 20 March 2013 at 02:03:31 UTC, Jonathan M Davis

wrote:
> We already get this. That's what == does by default. It's 
> just

> that it uses ==
> on each member, so if == doesn't work for a particular member
> variable and the
> semantics you want for == on the type it's in, you need to
> override opEquals.

Really?

string is one most people would like == to just work for. This
writes true then false. This certainly takes getting used to. 
It

alone is a good reason for the mixins and potentially a
non-member instancesDeepEqual.

import std.stdio;
struct S {
   string s;
}
void main() {
   writeln("foo" == "foo".idup);
   writeln(S("foo") == S("foo".idup));
}


That's a bug:

http://d.puremagic.com/issues/show_bug.cgi?id=3789



From Feb 2010. Maybe by now it is so understood how it works that 
at some point fixing it could be a problem. For some the language 
is better defined by how the compiler treats your code than what 
is listed in bugzilla. Even in looking through the history of 
that bug I could not find any definitive - some say its a bug, 
others say its not. You refer to TDPL which is a good source but 
if it is not viewed as a bug by Walter...


Re: recursive equal, and firstDifference functions

2013-03-19 Thread Dan
On Wednesday, 20 March 2013 at 02:03:31 UTC, Jonathan M Davis 
wrote:
We already get this. That's what == does by default. It's just 
that it uses ==
on each member, so if == doesn't work for a particular member 
variable and the
semantics you want for == on the type it's in, you need to 
override opEquals.


Really?

string is one most people would like == to just work for. This 
writes true then false. This certainly takes getting used to. It 
alone is a good reason for the mixins and potentially a 
non-member instancesDeepEqual.


import std.stdio;
struct S {
  string s;
}
void main() {
  writeln("foo" == "foo".idup);
  writeln(S("foo") == S("foo".idup));
}




Re: recursive equal, and firstDifference functions

2013-03-19 Thread Dan

On Tuesday, 19 March 2013 at 23:13:19 UTC, Jonathan M Davis wrote:

On Tuesday, March 19, 2013 22:43:10 Dan wrote:

The above works with the built-in AAs.
Please offer an example.


It works because the outer type defines toHash. Without toHash, 
the built-in
AAs won't work. If you're dealing with member variables which 
don't have
toHash, then doing something like you did is an option, but the 
outer type
still needs toHash, and if any of the member variables define 
an opEquals but
not a toHash, then you risk having your hash change when a 
member variable
changes even when the new value of the member variable is 
considered equal to
the old one (e.g. because a cached value or some other member 
variable in that
type is not considered to be part of the equality of an object 
but _would_ be
considered to be part of the hash if you use reflection to 
generate a hash from
all of that type's member variables). So, using reflection to 
generate hashes
for arbitrary types can be risky. Whether it works on not 
depends on how those

types are defined and what you're doing with them.



For hashing it is not foolproof as you mentioned. It is important 
to understand that opEquals and toHash should share the same 
semantics (i.e. if they are equal they should hash the same). 
But, in general, when you control the code you don't need toHash 
or opEquals at every level of composition and it will still work 
fine (compile-time recursively) as a key in a AA.


But the main problem that I'm pointing out is that you can't 
define your own,
non-standard functions for equality or hashing or whatever and 
expect your
types to play nicely with other stuff. If your stuff is wrapped 
in types that do
define the proper functions for that (like in your example), 
then it can work,
but the types which were wrapped won't play nice outside of the 
wrapper.




This is true, but then my code is by definition not standard. 
However, theoretically, the language writers could. For example, 
any '==' could be lowered to a 'standard' function, probably 
better named 'intancesDeepEqual(a,b)' and that function could use 
reflection to provide equal when not available else call opEquals 
if it is available. Similar with opCmp, dup, idup, ...
In other words, in the vein of the original poster, why not allow 
all of these nice goodies (equality comparison, opCmp comparison, 
dup) without requiring boilerplate code while still 
honoring/using it when it is provided.


Thanks
Dan


Re: recursive equal, and firstDifference functions

2013-03-19 Thread Dan

On Tuesday, 19 March 2013 at 21:11:12 UTC, Jonathan M Davis wrote:
Lots of stuff uses ==, toHash, etc. That's the way the language 
is designed.


Agreed

Defining your types without defining those properly just isn't 
going to work for
a _lot_ of stuff. Creating an external function to compare 
objects or generate
hashes or anything like that is just going to cause problems, 
because only

your stuff would use it.


Ok - you are making strong statement and I don't see why it is 
the case.


Here is an example that does work for hashing.
Note: R implements its own hash and just prints to show nothing 
up the sleeve.
Other classes (S,T) have no toHash implemented directly at all - 
yet you can see u1 and u3 resolve to the same hash and u2 a 
different, as you would expect.


-
import std.stdio;
import opmix.mix;
import pprint.pp;

struct R {
  string r;
  hash_t toHash() const nothrow {
try {
  writeln("toHash called on r");
} catch(Exception) {
}
return typeid(string).getHash(&r);
  }
}

struct S {
  R r;
  string s;
  string[int] si;
}

struct T {
  S s;
}

struct U {
  mixin ToHash;
  T t;
}

void main() {
  U u1 = U(T(S(R("a"), "foo", [1:"goo"])));
  U u2 = U(T(S(R("a"), "foo".idup)));
  U u3 = U(T(S(R("a"), "foo".idup, [1:"goo".idup])));

  writeln(deepHash(u1));
  writeln(deepHash(u2));
  writeln(deepHash(u3));

  writeln(pp(u1));

  int[U] aa;
  aa[u1] = 100;
  writeln("Is u1 in aa ", u1 in aa);
  writeln("Is u2 in aa ", u2 in aa);
  aa[u2] = 100;
  writeln("Is u2 in now aa ", u2 in aa);

}

--- OUTPUT --
toHash called on r
614624
toHash called on r
582446
toHash called on r
614624
{
 (U).t = {
  (T).s = {
   (S).r = {
(R).r = "a"
   }
   (S).s = "foo"
   (S).si = {
(K(1)[0] =>
 V("goo")),
   }
  }
 }
}
toHash called on r
toHash called on r
Is u1 in aa 7F2C7E556FC0
toHash called on r
Is u2 in aa null
toHash called on r
toHash called on r
Is u2 in now aa 7F2C7E556F40
--



The built-in stuff wouldn't, and the standard library
wouldn't. For instance, AAs require that opEquals and toHash be 
defined, and no
matter how clever your external functions for comparing objects 
or generating
hashes are, they're not going to work with the built-in AAs. 
Any type which is
going to work with the built-in AAs must define opEquals and 
toHash.




The above works with the built-in AAs.
Please offer an example.

Thanks
Dan


Re: recursive equal, and firstDifference functions

2013-03-19 Thread Dan

On Tuesday, 19 March 2013 at 20:28:09 UTC, Jonathan M Davis wrote:


Those are what opEquals, opCmp, and toHash are for. It might 
make sense to
define mixins which implement them for you (dealing with 
whatever recursive
semantics are necessary), but using external functions for 
those just isn't

going to fly.


Understand the sentiment. But you can easily have those external
functions call the member equivalents if they exist, and if not
still proceed and work. This is what they do, in fact. For 
instance,

it is nice to have the mixin for opCmp that actually calls member
opCmp if they exist. This opens the door a bit. It allows you to
have a reasonable opCmp for a type with a member that has none.

The same approach can be used for dup/gdup - which we have 
discussed

a few times now.


The language and standard library are designed around them being
part of the types themselves. Stuff like AAs won't work if 
those functions

aren't defined on the types themselves.



Sorry, I don't understand the last statement.




Re: recursive equal, and firstDifference functions

2013-03-19 Thread Dan

On Tuesday, 19 March 2013 at 17:08:54 UTC, timotheecour wrote:
I think none of you got the point of equalRecurse, so let me 
clarify.



I think I understand what you are after and I like the idea. I've
got a few:

-typesDeepEqual
-typesDeepCmp
-deepHash

Have a look at:
 
https://github.com/patefacio/d-help/blob/master/d-help/opmix/mix.d


Thanks
Dan


initializing const(Date)

2013-03-19 Thread Dan

This used to work but now in 2.062 it causes ctfe error.
Any suggested workaround?

http://dpaste.dzfl.pl/f1a8c2f5
-
import std.datetime;
const(Date) DefaultDate = Date(1929, 10, 29);
void main() {

}
-

Compilation output:
/opt/compilers/dmd2/include/std/datetime.d(13542): Error: 
Internal Compiler Error: CTFE literal cast(short)1
dmd: ctfeexpr.c:353: Expression* copyLiteral(Expression*): 
Assertion `0' failed.


Thanks
Dan


Re: Can D still compile html files? Seems not.

2013-02-26 Thread Dan Olson
Maybe you want Knuth's Literate Programming. 

http://en.wikipedia.org/wiki/Literate_programming

Long ago it was only for pascal and C (web and cweb), but now I see
there is noweb that works with any programming language.
-- 
Dan




Re: std.container.RedBlackTree versus C++ std::set

2013-02-16 Thread Dan
On Friday, 15 February 2013 at 20:58:30 UTC, Jonathan M Davis 
wrote:


I should probably add that bringing up discussions on how to 
solve problems in
the language can be of benefit, because they often result in 
good discussions
that help lead toward a solution, and that can lead towards 
that solution
ending up in the language (and depending on the discussion 
Andrei and/or
Walter will get involved). But simply asking them about the 
state of things or
essentially contronting them and trying to get them to give 
official statements
on their plans doesn't generally work. If nothing else, they 
simply don't
generally say what they're planning to do before they've 
actually decided on
it. They might start discussions to discuss something that 
they're
considering, but they're unlikely to state any kind of actual 
plans before
they've actually decided, which generally means no official 
statements about

what's coming or planned.

- Jonathan M Davis


Well, that is a somewhat passive yet diplomatic stance. If the 
suggestion is - "get involved, suggest a fix or a solution and 
maybe you'll get your answers" that is reasonable. But for my 
part, I am not a language developer - just a language user and 
fan of D who is betting on D by using it for my livelihood. 
Regarding postblits - you've mentioned several times that Andrei 
and Walter have discussed and have a solution in the works. Does 
it make sense to go do a DIP or something just to illicit 
feedback on a topic? You have some of the most helpful responses 
I've seen on the group - extremely detailed and accurate. Thanks. 
However, being in the know you sometimes you let slip a little 
bit here and there that causes me to give pause and at a minimum 
want to get more information. Like "And Walter was actually 
arguing at one point for making it illegal (probably by getting 
rid of postblit all together - I don't remember the details)".


It is not unreasonable for users to want to know what is the 
future direction for a certain at risk feature. Regarding a 
suggestion for postblit/copy ctor to get things going here is 
mine:


- Implement copy constructors for structs. Allow for overloading 
on 'this' and 'const this', but no qualifier on the constructor 
itself.

- Allow the user to @disable copy constructors.
- Provide for a default copy constructor that does regular copies 
of fundamental types, shallow copies of arrays and associative 
arrays,  and calls corresponding copy constructors (or postblits 
during some grace period).


In terms of migration path:

- Allow the struct designer to choose to use either postblit or 
copy constructor but not both. For the case of using them to 
provide deep copy semantics the approaches are different. For 
postblits you are asking - "what fields do I need to copy" with 
the comfort of knowing all other fields were already copied with 
the blit. For copy constructors it is different because you have 
to think about all fields since a blit will not have happened 
first. To ease the transition provide the ability for the copy 
constructor to call blitSourceIntoThis(source).


- Leave postblits alone. Allow them to continue as is and phase 
them out 1 or more years after successful implementation of copy 
constructors


- Often the only purpose of the copy constructor is to do a deep 
copy. This could easily be provided by the compiler or phobos. 
Further, consider standardizing on the ".dup" and ".idup" 
conventions for this purpose.


Thanks
Dan




Re: std.container.RedBlackTree versus C++ std::set

2013-02-15 Thread Dan
On Friday, 15 February 2013 at 23:41:50 UTC, Steven Schveighoffer 
wrote:
In any case, the example was bad, the point that which is 
better depends on the situation is still correct.


The compiler has to do something with "afundamental type it can avoid the lowering and just do whatever 
assembly is optimal. For a non-fundamental type, what is the case 
where (a.opCmp(b)<0) is more optimal than a comparable 
(a.opLess(b))?


It is easy to create an inefficient implementation of opCmp that 
calls "<" twice.


struct S {
   string s;
   int opCmp ( const ref S other ) {
 if ( sMy point was, you can use compile time reflection to generate a 
suitable opCmp that uses s.opCmp if it exists or does the long 
version of two comparisons if not.


Thanks
Dan


Re: std.container.RedBlackTree versus C++ std::set

2013-02-15 Thread Dan
On Thursday, 14 February 2013 at 19:31:36 UTC, Steven 
Schveighoffer wrote:


If it was pass by ref, then rbt.insert(5) would not work.  And 
in fact, I wouldn't want things passed by ref if the element is 
int.


What is the reason for the second objection - is just performance?
Is performance really an issue?

From this thread it looks like fundamental types by ref or value 
is not really a big deal in terms of performance. OTOH - as size 
and/or postblit execution gets expensive the cost *is* 
significant.

---
4 bytes: using cref_(int size) took 29[ms]
4 bytes: using inref(int size) took 29[ms]
4 bytes: using in___(int size) took 30[ms]

8 bytes: using cref_(int size) took 29[ms]
8 bytes: using inref(int size) took 28[ms]
8 bytes: using in___(int size) took 31[ms]
...

128 bytes: using cref_(int size) took 29[ms]
128 bytes: using inref(int size) took 29[ms]
128 bytes: using in___(int size) took 290[ms]
---


I have to admit, I did not consider expensive postblits when I 
designed it.  Almost all my testing is with integer types.




For performance, it seems by ref should always be preferred in 
generic code because you can not know the cost of postblit - or 
copy construction if that were a future solution for structs. 
Granted the no rvalue passing is a pain - but is it a big deal in 
library/generic code?


Thanks,
Dan


Re: std.container.RedBlackTree versus C++ std::set

2013-02-15 Thread Dan
On Thursday, 14 February 2013 at 20:53:26 UTC, Jonathan M Davis 
wrote:


And Walter and Andrei both seem to think that having expensive 
postlbits is a
design mistake. The range stuff sort of tries to support it 
with the move*
primitives, but Andrei's been wanting to argue for just 
assuming that
postblits are cheap. And Walter was actually arguing at one 
point for making
it illegal (probably by getting rid of postblit all together - 
I don't
remember the details). Plenty of the rest of us don't agree, 
but to some
extent, it is true that having an expensive postblit is asking 
for it. On a
related note, we still need a solution for dealing with const 
postblits
(probably be introducing copy constructors - IIRC Andrei was 
considering
phasing out postblits in favor of copy constructors, which 
would be
unnecessary, but we do need a way to deal with deep copying 
const structs

which hold reference types which need to be deep copied.



When you say things like "Andrei was considering phasing out 
postblits..." I get nervous. Can we please have some comments 
from Andrei/Walter about what the plans are? I'm not asking for 
the ultimate solution - just to know the general direction and 
where this issue stands at present. Is there anything any of us 
can do to help move this forward?


Regarding replacing expensive postblits with copy constructors - 
how does that help? The expense will remain the same - if you 
need a transitive copy, you need a transitive copy.


Thanks
Dan




Re: std.container.RedBlackTree versus C++ std::set

2013-02-15 Thread Dan
On Friday, 15 February 2013 at 17:42:30 UTC, Steven Schveighoffer 
wrote:
On Fri, 15 Feb 2013 12:11:55 -0500, monarch_dodra 
 wrote:


Also keep in mind that "a < b" is implemented as two calls to 
"a.opCmp(b)", and "a.opCmp(b)" is itself usually implemented 
as two calls to "something < something else" (!)


Huh?

a < b is implemented as a.opCmp(b) < 0, not two calls to 
a.opCmp(b).


Yes. But isn't opCmp still more work than just abecause it returns three states instead of two. So, I think the 
general warning on opCmp is warranted especially with structs. 
For structs we could use compile time reflection to provide 
automatic efficient opCmp behavior. Section 3.1 here outlines a 
way:


https://github.com/patefacio/d-help/blob/master/doc/canonical.pdf

Any comments appreciated.

Thanks
Dan



HOWEVER, when you get to the point of executing a == b, it's 
implemented as !(a < b) && !(b < a), which could more 
efficiently be rewritten as a.opEquals(b) or a.opCmp(b) == 0.




rdmd hung?

2013-02-15 Thread Dan
I use emacs and have command that runs rdmd. Very rarely, as a 
guess maybe one in 100 calls to build, rdmd does not make any 
progress and I have to kill it. So, a ps -efww shows something 
like below and over 15 minutes have passed (normally max time to 
build and run is a couple of seconds)


UIDPID  PPID  C STIME TTY  TIME CMD
1000  4065  4063  0 10:44 pts/12   00:00:00 rdmd -debug -g -w 
-property foo.d


No progress is being made.
So, my questions:
- is this a potential deadlock in rdmd? I believe it attempts to 
parallelize the work.

- has anyone experienced this?
- on linux is there a way, once in this state to provide any 
information that would be helpful. strace during on a complete 
run could help - but it is too late for that.


Thanks
Dan


Re: best idiom for insert if not present; else use value in assoc array

2013-02-09 Thread Dan
On Saturday, 9 February 2013 at 00:54:58 UTC, Andrej Mitrovic 
wrote:

Feel free to file an enhancement request.


http://d.puremagic.com/issues/show_bug.cgi?id=9491

Hopefully that is clear.


  1   2   3   >