Re: += on associative arrays leads to surprising result

2019-08-27 Thread Samir via Digitalmars-d-learn

On Tuesday, 27 August 2019 at 16:12:07 UTC, berni wrote:

What's your oppinion on this?


As someone relatively new to programming in general and to D in 
particular, this behavior does, on the surface, seem 
inconsistent.  Good to see that a bug exists for this, per 
ag0aep6g.


I never understood why the intial value of floats, doubles and 
reals was NaN.


Samir


Re: Sort Associative Array by Key

2019-08-27 Thread Samir via Digitalmars-d-learn

On Sunday, 25 August 2019 at 17:01:23 UTC, a11e99z wrote:

auto foo = ["VXE":8, "BZP":5, "JLC":2];
foo.byPair.array.sort!"a[0]

On Sunday, 25 August 2019 at 19:03:10 UTC, JN wrote:

I think normal lambdas are better than these string ones:

foo.byPair.array.sort!((a, b) => a[0] < b[0]).map!(a => 
a[1]).writeln;


On Sunday, 25 August 2019 at 21:13:05 UTC, Paul Backus wrote:

You can also use names instead of numeric indices:

foo.byPair.array.sort!((a, b) => a.key < b.key).map!(a => 
a.value);


a11e99z, JN, Paul:  Thank you all for your replies and help.  As 
I've mentioned on the list before, I really struggle to 
understand how some of the std.algorithm functions such as `map` 
work when combined with things like `array`, `sort` and 
especially `zip` but really appreciate the support I find here on 
the forum.


Samir




Sort Associative Array by Key

2019-08-25 Thread Samir via Digitalmars-d-learn
Is there a way to output the values of an associative array based 
on the lexicographic order of the keys?


For example, if foo = ["VXE":8, "BZP":5, "JLC":2], I'd like to 
output something like:


5
2
8

Thanks!
Samir


Re: Finding Max Value of Column in Multi-Dimesional Array

2019-07-06 Thread Samir via Digitalmars-d-learn

On Friday, 5 July 2019 at 19:56:54 UTC, ag0aep6g wrote:
It works when you pass an actual callable instead, e.g. a 
lambda:


p.map!(a => a[column]).maxElement.writeln;


On Friday, 5 July 2019 at 20:22:14 UTC, dwdv wrote:
Furthermore, Samir, the parameter `a` can be renamed to 
whatever you prefer or what fits the code at hand best, e.g. 
`(row => row[column])`, as opposed to the string version, where 
only a small set of mostly single character names is supported.


Thank you very much for the explanation!  As I've mentioned 
before, I have a lot to learn about the `map` function and the 
details provided here help immensely.


Samir


Re: Finding Max Value of Column in Multi-Dimesional Array

2019-07-05 Thread Samir via Digitalmars-d-learn

On Friday, 5 July 2019 at 00:54:15 UTC, Samir wrote:
Is there a cleaner way of finding the maximum value of say the 
third column in a multi-dimensional array than this?

int[][] p = [[1,2,3,4], [9,0,5,4], [0,6,2,1]];
writeln([p[0][2], p[1][2], p[2][2]].max);

I've tried the following
writeln([0, 1, 2].map!(p[a][2]).max);

but get an "Error: undefined identifier a" error.


As a follow-on to my earlier question, is there a way to pass a 
variable to the `map` function that specifies the column, rather 
than hard-coding it?  I'm thinking of something like:


p.map!("a[column]").maxElement.writeln;

In the mean time, I am looking further into Ilya's mir-algorithm 
library.


Thanks
Samir


Re: To learn D

2019-07-05 Thread Samir via Digitalmars-d-learn

On Friday, 5 July 2019 at 13:56:18 UTC, Craig Dillabaugh wrote:
Ali's book is targeted at beginners (see link below).  I don't 
see why D wouldn't make a good first language.  If your 
objective is to learn D, then I don't think learning C or 
Python is going to be help that much.  Obviously if you know 
C/Python you can learn D more quickly, but I doubt the effort 
is worth it if D is the ultimate goal.


http://ddili.org/ders/d.en/index.html


I will second Craig's recommendation to spend some time going 
through Ali's book.  It strikes a good balance between being an 
introduction to programming in general, and to D in particular.  
While I have dabbled in half a dozen languages or so over the 
years, I find D to be a lot more accessible than many of the 
other languages I've tried.  Part of that comes do the language 
design (similarities to C and Python) but mostly to the helpful 
community you will find here.  Good luck!





Re: Finding Max Value of Column in Multi-Dimesional Array

2019-07-05 Thread Samir via Digitalmars-d-learn

On Friday, 5 July 2019 at 01:41:38 UTC, 9il wrote:

You may want to take a look into mir-algorithm [1] library.
It contains ndsilce package [2] to work with multidimensional 
data.


Thanks for referring me to this library, Ilya.  I will have to 
check this out.  While it seems a bit more complicated for my 
particular use case, this definitely seems like something worth 
checking out for future use!


On Friday, 5 July 2019 at 03:02:29 UTC, Jordan Wilson wrote:

p.map!"a[2]".maxElement.writeln; // 5


Thank you, Jordan.  I think this is what I was looking for.  I am 
still struggling to wrap my head around the use of `map` but 
these examples really help.


Samir


Finding Max Value of Column in Multi-Dimesional Array

2019-07-04 Thread Samir via Digitalmars-d-learn
Is there a cleaner way of finding the maximum value of say the 
third column in a multi-dimensional array than this?

int[][] p = [[1,2,3,4], [9,0,5,4], [0,6,2,1]];
writeln([p[0][2], p[1][2], p[2][2]].max);

I've tried the following
writeln([0, 1, 2].map!(p[a][2]).max);

but get an "Error: undefined identifier a" error.

I know there doesn't seem to be much of a difference between two 
examples but my real-world array is more complex which is why I'm 
looking for a more scalable option.


Thanks
Samir


Re: Finding the maxElement of Two-Dimensional Array

2019-06-30 Thread Samir via Digitalmars-d-learn

On Sunday, 30 June 2019 at 15:38:42 UTC, a11e99z wrote:

try to take slice from static arrays
writeln(ta[1][].maxElement);


That does what I am looking for.  Thank you for the quick reply!


Finding the maxElement of Two-Dimensional Array

2019-06-30 Thread Samir via Digitalmars-d-learn

How come this works:

int[][] ta = [[2, 1, 4, 3], [3, 10, 2, 5]];
writeln(ta[1].maxElement); // 10

but I get an error when specifying the number of elements when 
declaring the array:


int[4][2] ta = [[2, 1, 4, 3], [3, 10, 2, 5]];
writeln(ta[1].maxElement); // get error on this line

Error: template std.algorithm.searching.maxElement cannot deduce 
function from argument types !()(int[4]), candidates are:

/home/samir/dlang/dmd-2.082.0/freebsd/bin64/../../src/phobos/std/algorithm/searching.d(3576):
std.algorithm.searching.maxElement(alias map = (a) => a, Range)(Range r) if 
(isInputRange!Range && !isInfinite!Range)
/home/samir/dlang/dmd-2.082.0/freebsd/bin64/../../src/phobos/std/algorithm/searching.d(3583):  
  std.algorithm.searching.maxElement(alias map = (a) => a, Range, RangeElementType = 
ElementType!Range)(Range r, RangeElementType seed) if (isInputRange!Range && 
!isInfinite!Range && !is(CommonType!(ElementType!Range, RangeElementType) == void))

Thanks
Samir


Re: Using std.algorithm.iteration to Calculate Hamming Distance

2019-06-23 Thread Samir via Digitalmars-d-learn

On Sunday, 23 June 2019 at 13:29:25 UTC, KnightMare wrote:

zip( "hello world", "Hello World" ).map!"a[0] != a[1]".sum


Excellent!  Thank you!


Using std.algorithm.iteration to Calculate Hamming Distance

2019-06-23 Thread Samir via Digitalmars-d-learn
D already has a function to calculate the Levenshtein 
distance[1].  I am trying to come up with a function to calculate 
the Hamming distance[2] between two strings, `a` and `b`.  So 
far, this seems to work:


foreach (i, j; zip(a, b)) {
if (i != j)
++hammingDistance;
}

Is there a way to use any of the std.algorithm.iteration[3] 
algorithms such as `filter` or `map` to do this as well?


[1] 
https://dlang.org/phobos/std_algorithm_comparison.html#levenshteinDistance

[2] https://en.wikipedia.org/wiki/Hamming_distance
[3] https://dlang.org/phobos/std_algorithm_iteration.html


Re: Range violation error when reading from a file

2019-06-20 Thread Samir via Digitalmars-d-learn

On Tuesday, 18 June 2019 at 09:42:41 UTC, aliak wrote:

On Tuesday, 18 June 2019 at 01:15:54 UTC, Samir wrote:

On Monday, 17 June 2019 at 03:46:11 UTC, Norm wrote:
That's because you're using write*ln*. So even though line is 
empty, you still output a new line.


Curious.  I am going to have to think about that for a bit as 
I don't quite understand.


I mean this:

$ dmd -run readfile.d
1)
file.eof() == false
line = "> line 1"
writeln("lines 1" + \n);
2)
file.eof() == false
line = line 2
writeln("line 2" + \n);

...snip...

6)
file.eof() == false
line = "" // empty since there're no lines left in file
writeln("" + \n); <-- this is your blank line
7)
file.eof() == true


Got it!  Now I see what you were saying.  Thanks for taking the 
time to provide a detailed explanation!


Re: Range violation error when reading from a file

2019-06-17 Thread Samir via Digitalmars-d-learn

On Monday, 17 June 2019 at 03:46:11 UTC, Norm wrote:

On Monday, 17 June 2019 at 00:22:23 UTC, Samir wrote:



Any suggestions on how to rectify?


You could change the IF to

`if(line.length > 0 && line[0] == '>')`


Thanks, Norm.  That seemed to do the trick and fixed the error.

On Monday, 17 June 2019 at 11:25:01 UTC, aliak wrote:

On Monday, 17 June 2019 at 00:22:23 UTC, Samir wrote:


HOWEVER, the output is interesting.  There IS a blank line 
between the last line and the prompt:


That's because you're using write*ln*. So even though line is 
empty, you still output a new line.


Curious.  I am going to have to think about that for a bit as I 
don't quite understand.



Any suggestions on how to rectify?



You can do:

if (!line.length) {
continue;
}

Inside your while loop after the call to strip.


Thanks, aliak!  I think this is similar to Norm's suggestion in 
that I need to check for a non-zero line length before continuing.


What's funny now is that I get two blank lines after the output 
and before the prompt:


$ ./readfile
 line 1
line 2
line 3
 line 4
line 5


$

Ultimately, I think the original suggestions by you and lithium 
iodate about there being an empty line at the end is probably the 
culprit.  I will have to investigate that further.


Thank you to everyone that chimed in to help me out!


Re: Range violation error when reading from a file

2019-06-16 Thread Samir via Digitalmars-d-learn

On Sunday, 16 June 2019 at 23:55:41 UTC, lithium iodate wrote:
There is *very* likely to be a terminating new-line at the end 
of the file (many editors add one without asking!). If that the 
case, the last line seen by the loop will be empty and you must 
not attempt to access any elements.


On Monday, 17 June 2019 at 00:02:37 UTC, aliak wrote:
The fail bit is only set after reading fails. So after you read 
the last line, your eof will still return true, and hence your 
range violation.


H...maybe you and lithium iodate were onto something.

Here is what the file looks like in vim:
> line 1
line 2
line 3
> line 4
line 5
~
~
~

The "5" in the last line is the last character I can put my 
cursor on.


Also, if I run the program below with the same file, I don't get 
any range violation errors:


import std.stdio;
import std.string;

void main() {
File file = File("test.txt");
string line;

while (!file.eof()) {
line = file.readln().strip;
//if (line[0] == '>') { // line 10
//writeln(line[1..$]);
//}
//else {
writeln(line);
//}
}
}

HOWEVER, the output is interesting.  There IS a blank line 
between the last line and the prompt:


$ dmd -run readfile.d
> line 1
line 2
line 3
> line 4
line 5

$

Any suggestions on how to rectify?



Re: Range violation error when reading from a file

2019-06-16 Thread Samir via Digitalmars-d-learn

On Sunday, 16 June 2019 at 23:03:04 UTC, aliak wrote:

stripping the last line could result in an empty line if it 
just has strippable characters?


The last line of the file is just text but without a newline (\n) 
character or any other whitespace character at the end.  I get 
the same error when I remove the strip function from the readln 
line.


Re: Range violation error when reading from a file

2019-06-16 Thread Samir via Digitalmars-d-learn

On Sunday, 16 June 2019 at 23:03:04 UTC, aliak wrote:
stripping the last line could result in an empty line if it 
just has strippable characters?


The last line is just the text of the last line.  There is no 
newline character at the end.  I also get the same error if I 
remove the strip function from the readln line.


Range violation error when reading from a file

2019-06-16 Thread Samir via Digitalmars-d-learn

I am trying to read from a text file using the following code:

import std.stdio;
import std.string;

void main() {
File file = File("test.txt");
string line;

while (!file.eof()) {
line = strip(file.readln());
if (line[0] == '>') { // line 10
writeln(line[1..$]);
}
else {
writeln(line);
}
}
}

and I get the following error AFTER the last line is processed:

core.exception.RangeError@readfile.d(10): Range violation

??:? _d_arrayboundsp [0x448efa]
??:? _Dmain [0x4459f7]

Any idea what I am doing wrong?  When processing the if statement 
or writing the slice, am I inadvertently trying to read a 
non-existent line in the file?


Thanks in advance
Samir


Re: Help with Regular Expressions (std.regex)

2019-03-05 Thread Samir via Digitalmars-d-learn

On Monday, 4 March 2019 at 18:57:34 UTC, dwdv wrote:

There is also std.file.slurp which makes this quite easy:
slurp!(int, int, int, int, int)("03.input", "#%d @ %d,%d: 
%dx%d");


That's brilliant!  This language just keeps putting a smile on my 
face every time I learn something new like this!


Re: Help with Regular Expressions (std.regex)

2019-03-04 Thread Samir via Digitalmars-d-learn

On Sunday, 3 March 2019 at 19:27:17 UTC, user1234 wrote:

oops forgot the bang

  auto allMatches = matchAll(line, pattern).map!(a => 
a.hit).array;


Thanks, user1234!  Looks like `map` is another topic I need to 
read up upon.  I slightly modified your suggestion and went with:


auto allMatches = matchAll(line, pattern).map!(a => 
to!int(a.hit)).array;


which also takes care of converting the string to int.

Samir



Help with Regular Expressions (std.regex)

2019-03-03 Thread Samir via Digitalmars-d-learn
I am belatedly working my way through the 2018 edition of the 
Advent of Code[1] programming challenges using D and am stumped 
on Problem 3[2].  The challenge requires you to parse a set of 
lines in the format:

#99 @ 652,39: 24x23
#100 @ 61,13: 15x24
#101 @ 31,646: 16x28

I would like to store each number (match) as an element in an 
array so that I can refer to them by index.  For example, for the 
first line:


m = [99, 652, 39, 24, 23]
assert(m[0] == 99);
assert(m[1] == 652);
// ...
assert(m[4] == 23);

What is the best way to do this?  (I will worry about converting 
characters to integers later.)


I have the following solution so far based on reading Dmitry 
Olshansky's article on std.regex[3] and the std.regex 
documention[4]:


import std.stdio;
import std.regex;

void main() {
auto line= "#99 @ 652,39: 24x23";
auto pattern = regex(r"\d+");
auto m   = matchAll(line, pattern);
writeln(m);
}

which results in:
[["99"], ["652"], ["39"], ["24"], ["23"]]

But this doesn't seem to be an iterable array as changing 
writeln(m) to writeln(m[0]) yields

Error: no [] operator overload for type RegexMatch!string

Changing the line to writeln(m.front[0]) yields
99

but m.front doesn't allow me to access other elements (i.e. 
m.front[1]):

requested submatch number 1 is out of range

??:? _d_assert_msg [0x4dc27a]
??:? inout pure nothrow @trusted inout(immutable(char)[]) 
std.regex.Captures!(immutable(char)[]).Captures.opIndex!().opIndex(ulong) [0x4d8d57]

??:? _Dmain [0x49ffc8]

I've tried something like
foreach (m; matchAll(line, pattern))
writeln(m.hit);

which is close but doesn't result in an array.  Do I need to use 
matchFirst?


Thanks in advance.
Samir

[1] https://adventofcode.com/2018
[2] https://adventofcode.com/2018/day/3
[3] https://dlang.org/articles/regular-expression.html
[4] https://dlang.org/phobos/std_regex.html


Re: Error with matplotlib

2019-02-19 Thread Samir via Digitalmars-d-learn

On Tuesday, 19 February 2019 at 11:57:00 UTC, Andre Pany wrote:
The python script generates a list of available functions in 
the python package.

This list will be used to generate D coding at compilation time.
That is the reason, the error occurs in a mixin.
Unfortunately one function had the same name as a D keyword (it 
was the keyword deprecated). The fix was to exclude this 
function from the list.


I think this is the only dub package working this way, as it 
might be the only

package which wrapping python code.


Thanks again for all of your help and explanations, Andre!


Re: Error with matplotlib

2019-02-18 Thread Samir via Digitalmars-d-learn

On Monday, 18 February 2019 at 21:50:25 UTC, Andre Pany wrote:
In the meantime you could adapt the python script on your local 
file system in the dub packages cache folder as described here 
https://github.com/koji-kojiro/matplotlib-d/pull/11/files


Andre,

Thank you very much for your help today!

I copied the version of prebuild.py located here[1] and replaced 
the version located at 
/home/samir/.dub/packages/matplotlib-d-0.1.4/matplotlib-d/python 
locally on my machine after which the program ran.


I guess I still have the question as to why does the error 
message refer to issues in 
/home/samir/.dub/packages/matplotlib-d-0.1.4/matplotlib-d/source/matplotlibd/pyplot.d-mixin-41 when the solution was changing /home/samir/.dub/packages/matplotlib-d-0.1.4/matplotlib-d/python/prebuild.py?


Apologies for all of the questions -- I'm just trying to better 
understand how to incorporate other packages in my simple 
programs.


Samir

[1] 
https://github.com/koji-kojiro/matplotlib-d/blob/master/python/prebuild.py


Re: Error with matplotlib

2019-02-18 Thread Samir via Digitalmars-d-learn

On Monday, 18 February 2019 at 20:30:23 UTC, Andre Pany wrote:
The issue is, the dub package is using python 2 (it executes 
application python) while you have installed matplotlib for 
Python 3 (application python3).


Thank you for that!  After installing the version of matplotlib 
for python2 and rerunning dub build, I now get the following 
error:


$ dub build
Performing "debug" build using 
/usr/home/samir/dlang/dmd-2.082.0/freebsd/bin64/dmd for x86_64.

matplotlib-d 0.1.4: building configuration "library"...
Running pre-build commands...
/home/samir/.dub/packages/matplotlib-d-0.1.4/matplotlib-d/source/matplotlibd/pyplot.d-mixin-41(191,6):
 Error: no identifier for declarator void
/home/samir/.dub/packages/matplotlib-d-0.1.4/matplotlib-d/source/matplotlibd/pyplot.d-mixin-41(191,18):
 Error: found ... when expecting )
/home/samir/.dub/packages/matplotlib-d-0.1.4/matplotlib-d/source/matplotlibd/pyplot.d-mixin-41(191,21):
 Error: declaration expected, not )
/home/samir/.dub/packages/matplotlib-d-0.1.4/matplotlib-d/source/matplotlibd/pyplot.d-mixin-41(191,63):
 Error: declaration expected, not if
/home/samir/.dub/packages/matplotlib-d-0.1.4/matplotlib-d/source/matplotlibd/pyplot.d-mixin-41(191,89):
 Error: no identifier for declarator a
/home/samir/.dub/packages/matplotlib-d-0.1.4/matplotlib-d/source/matplotlibd/pyplot.d-mixin-41(191,89):
 Error: declaration expected, not )
/usr/home/samir/dlang/dmd-2.082.0/freebsd/bin64/dmd failed with 
exit code 1.


I don't see a pyplot.d-mixin-41 file in that directory but I do 
have pyplot.d.


Is there an issue with the package itself?

Samir


Re: Windows Defender won't let me install DMD

2019-02-18 Thread Samir via Digitalmars-d-learn

On Monday, 18 February 2019 at 19:44:56 UTC, Samir wrote:
that is what the two reference books[1] I am using to learn D 
have been using.


Idiot me forgot to mention the two resources I have been using:
(1) "Programming in D", by Ali Çehreli, available at 
http://ddili.org/ders/d.en/index.html
(2) "Learning D", by Michael Parker, available at 
https://www.packtpub.com/application-development/learning-d


Re: Windows Defender won't let me install DMD

2019-02-18 Thread Samir via Digitalmars-d-learn

On Monday, 18 February 2019 at 16:32:26 UTC, belkin wrote:

Obviously I need a compiler (which one is best ).


I too am a beginner (both at programming and at D).  I have been 
sticking to the dmd compiler (over others such as gdc or ldc) 
mainly because that is what the two reference books[1] I am using 
to learn D have been using.


But I also want an IDE and so far it seems Visual D would be a 
best choice.


I've been using vim as the syntax highlighting seems to work 
pretty well out of the box but mainly because I am not familiar 
with any IDEs.  Personally, I find that keeping things simple at 
this point are probably better for the way I work and learn.


The good news is that I have found the people here to be quite 
friendly and helpful when you run into issues.


Good luck!
Samir


Re: Error with matplotlib

2019-02-18 Thread Samir via Digitalmars-d-learn

On Monday, 18 February 2019 at 18:27:17 UTC, Andre Pany wrote:
Therefore python needs to be installed and also 
matplotlib.pyplot.


Hi Andre,

I do have both python3 and matplotlib installed:

 $ python3
 Python 3.6.7 (default, Jan 10 2019, 01:15:48)
 [GCC 4.2.1 Compatible FreeBSD Clang 6.0.0 
(tags/RELEASE_600/final 326565)] on freebsd11
 Type "help", "copyright", "credits" or "license" for more 
information.

 >>> matplotlib.__version__
 '3.0.2'
 >>> import matplotlib.pyplot
 >>>

Do I have an issue with the way my dub.json file is configured?  
This is the first time I am using dub.  I also just copied and 
pasted the code in app.d straight from the matplotlib-d package 
page (http://code.dlang.org/packages/matplotlib-d).


Thanks
Samir


Error with matplotlib

2019-02-17 Thread Samir via Digitalmars-d-learn
I am trying to run the code from the "Simple Example" listed in 
the matplotlib-d package page[1] and am running into the 
following error:


$ dub build
Performing "debug" build using 
/usr/home/samir/dlang/dmd-2.082.0/freebsd/bin64/dmd for x86_64.

matplotlib-d 0.1.4: building configuration "library"...
Running pre-build commands...
Traceback (most recent call last):
  File 
"/home/samir/.dub/packages/matplotlib-d-0.1.4/matplotlib-d/python/prebuild.py", line 37, in 

gen_pyplot_functions(argv[1])
  File 
"/home/samir/.dub/packages/matplotlib-d-0.1.4/matplotlib-d/python/prebuild.py", line 25, in gen_pyplot_functions

import matplotlib.pyplot
ImportError: No module named matplotlib.pyplot
Command failed with exit code 1: python 
/home/samir/.dub/packages/matplotlib-d-0.1.4/matplotlib-d/python/prebuild.py /home/samir/.dub/packages/matplotlib-d-0.1.4/matplotlib-d


Some information about my environment:
$ uname -a
FreeBSD enterprise 11.2-RELEASE-p9 FreeBSD 11.2-RELEASE-p9 #0: 
Tue Feb  5 15:30:36 UTC 2019 
r...@amd64-builder.daemonology.net:/usr/obj/usr/src/sys/GENERIC  
amd64

$ dmd --version
DMD64 D Compiler v2.082.0
Copyright (C) 1999-2018 by The D Language Foundation, All Rights 
Reserved written by Walter Bright

$ python3
Python 3.6.7 (default, Jan 10 2019, 01:15:48)
[GCC 4.2.1 Compatible FreeBSD Clang 6.0.0 (tags/RELEASE_600/final 
326565)] on freebsd11
Type "help", "copyright", "credits" or "license" for more 
information.

import matplotlib
matplotlib.__file__

'/usr/local/lib/python3.6/site-packages/matplotlib/__init__.py'

matplotlib.__version__

'3.0.2'

dub.json:
{
"name": "matplotlib",
"authors": [
"User &"
],
"description": "A minimal D application.",
"copyright": "Copyright _ 2019, User &",
"license": "proprietary",
"dependencies": {
"matplotlib-d": "~>0.1.4"
}
}

source/app.d:
import std.math;
import std.range;
import std.algorithm;
import plt = matplotlibd.pyplot;

void main() {
 auto x = iota(0, 2.05, 0.05).map!(x => x * PI);
 auto y = x.map!(sin);

 plt.plot(x, y, "r-", ["label": "$y=sin(x)$"]);
 plt.xlim(0, 2 * PI);
 plt.ylim(-1, 1);
 plt.legend();
 plt.savefig("simple.png");
 plt.clear();
}

[1] http://code.dlang.org/packages/matplotlib-d


Re: 9999999999999999.0 - 9999999999999998.0

2019-01-06 Thread Samir via Digitalmars-d-learn

On Sunday, 6 January 2019 at 01:05:08 UTC, Adam D. Ruppe wrote:
That's because it is done at compile time, since both are 
compile-time constants. The compiler will evaluate it using the 
maximum precision available to the compiler, ignoring your 
request to cast it to double (which annoys some people who 
value predictability over precision btw). At different 
precisions, you get different results.


Thanks for that explanation, Adam!  Very helpful.

On Sunday, 6 January 2019 at 03:33:45 UTC, Jesse Phillips wrote:

Since you got your answer you may also like
http://dconf.org/2016/talks/clugston.html


Thank you for pointing out that talk, Jesse.  I will set aside 
some time to go through that!


Samir


9999999999999999.0 - 9999999999999998.0

2019-01-05 Thread Samir via Digitalmars-d-learn
I saw the following thread[1] today on Hacker News that discusses 
an article that compares how various languages compute 
.0 - 9998.0.  A surprisingly large 
number of languages return 2 as the answer.  I ran the following 
which returned 1:


import std.stdio: writeln;
void main(){
writeln(cast(double).0-9998.0);
}

I don't know anything about IEEE 754[2] which, according to the 
HN discussion, is the standard for floating point arthimetic, but 
was pleasantly surprised to see how D handles this.  Does anyone 
know why?


Thanks
Samir

[1] https://news.ycombinator.com/item?id=18832155
[2] https://en.wikipedia.org/wiki/IEEE_754


Re: Writing Program Without main Function

2018-12-08 Thread Samir via Digitalmars-d-learn
On Saturday, 8 December 2018 at 03:30:30 UTC, Jonathan M Davis 
wrote:
There's one main per program, not per module. Where main lives 
depends on how the program was written, but dub encourages 
putting it in app.d, because that's what it generates when you 
create a new dub project. imports then provide access to other 
modules so that the code doing the importing can use it. You 
can think of it like the module with main being the start of 
the import tree, though it's a bit more complicated than that 
in practice, since modules can be compiled separately, and main 
only has to be there when the program is finally linked. But in 
concept, you have main and the module its in importing other 
modules, which then import other modules, etc. until you get 
all of the code in the program.


- Jonathan M Davis


Thanks for all of the great feedback and explanations, Jonathan!  
Looks like I need to add dub to the list of things I still need 
to learn about.


Re: Writing Program Without main Function

2018-12-07 Thread Samir via Digitalmars-d-learn
Ok.  Upon further investigation, I think I see what is going on.  
Most of the repos I am skimming are for this year's Advent of 
Code.  They structure their repo with an `app.d` file which does 
contain a `main` function but this program is structured such 
that it imports the files I was looking at earlier (which do not 
have a `main` function).


Looks like I have to get smarter on how modules, mixins and 
imports work.


Writing Program Without main Function

2018-12-07 Thread Samir via Digitalmars-d-learn
Is it possible to write and execute a D program without a main 
function?


Most of my programs will start with some `import` statements, 
followed by any functions and then ending with the `main` 
function (e.g. `void main() {`).


As I am just a beginner to programming and still new to D, I have 
been browsing some repositories that people have posted here to 
learn more about the language and how more experienced 
programmers write their code.  In many of these examples, they 
start with the `module` statement followed by their `import` 
statements and then will have sections defining various classes, 
structs, unit tests and other bits but I never see a `main` 
function.


How do you compile and execute these programs?

Thanks
Samir


Re: Why is dynamic array length required here?

2018-10-21 Thread Samir via Digitalmars-d-learn
Stanislav, Ali, Mike -- Thank you all for your thoughtful and 
helpful replies to my queries.  Apologies that it has taken this 
long to reply to you.  I still haven't been able to find time to 
go through all of the code examples provided but hope to do so 
later this week.  If I have additional questions, I know where to 
go!


Thanks again!


Why is dynamic array length required here?

2018-10-18 Thread Samir via Digitalmars-d-learn
I am working my way through the exercises in the "Programming in 
D" tutorial (http://ddili.org/ders/d.en/arrays.html).  Why is the 
line assigning the length of the dynamic array required?


/*
Write a program that asks the user how many values will be 
entered and then
reads all of them. Have the program sort the elements using 
sort() and then

reverse the sorted elements using reverse().
*/

import std.stdio;
import std.algorithm;

void main() {
int noValues, i;
int[] myArray;

write("how many values would you like to enter? ");
readf(" %s", );
myArray.length = noValues; // I get a run-time error if I 
comment this out


while (i < noValues) {
write("enter value #", i+1, " ");
readf(" %s", [i]);
++i;
}

sort(myArray);
writeln(myArray);
reverse(myArray);
writeln(myArray);

}

Without the line:

myArray.length = noValues;

I get the run-time error:

$ ./exArrays1_1
how many values would you like to enter? 5
core.exception.RangeError@exArrays1_1.d(12): Range violation

??:? _d_arrayboundsp [0x461772]
??:? _Dmain [0x44c284]

I would have thought that since this is a dynamic array, I don't 
need to pre-assign its length.


Thanks




Re: How to store unique values of array in another array

2018-10-18 Thread Samir via Digitalmars-d-learn

On Thursday, 18 October 2018 at 19:25:26 UTC, Adam D. Ruppe wrote:

Which is better simply depends on which one reads better to you.


Thanks again, Adam.


Re: How to store unique values of array in another array

2018-10-18 Thread Samir via Digitalmars-d-learn

On Thursday, 18 October 2018 at 18:53:06 UTC, Adam D. Ruppe wrote:
But, if you need to copy it into a new array, use `.array` at 
the end.


Thanks.  That did the trick.  But if I may, what is the 
difference between


uniqueArray = uniq(sort(unsortedArray)).array;

and

uniqueArray = unsortedArray.sort().uniq.array;

They both seem to work.  Is one preferred over the other?



How to store unique values of array in another array

2018-10-18 Thread Samir via Digitalmars-d-learn
What is the proper way to find the unique values of an array and 
store them in another array?  When I try:


import std.stdio: writeln;
import std.conv;
import std.algorithm;

void main() {
int[] unsortedArray = [5, 3, 8, 5, 2, 3, 0, 8];
int[] uniqueArray;

uniqueArray = uniq(sort(unsortedArray));
}

I get the compilation error:
sortSetUnique2.d(9): Error: cannot implicitly convert expression 
uniq(sort(unsortedArray)) of type UniqResult!(binaryFun, 
SortedRange!(int[], "a < b")) to int[]


which leads me to believe that the output of `uniq` is not 
necessarily another integer array.


Thanks


Re: "Error: function expected before (), not module *module* of type void

2018-09-21 Thread Samir via Digitalmars-d-learn
On Saturday, 22 September 2018 at 01:58:57 UTC, Adam D. Ruppe 
wrote:
You probably shouldn't name a module the same as a member 
anyway, and it should also have two names, like "module 
myproject.isprime;"


But the fix here is to just use the full name.

import isPrime;
void main() {
  isPrime.isPrime(x); // module_name.member_name
}

or change the import:

import isPrime : isPrime; // specify you want the same-named 
member



Both files are in the same directory. When compiling main.d,


When compiling, be sure to pass both modules to it, or use the 
dmd -i if on a new version.


dmd -i main.d

or

dmd main.d isPrime.d

main.d:(.text._Dmain[_Dmain]+0x83): undefined reference to 
`_D7isPrime3isPFiZb'


this likely means you forgot to compile in the isPrime module, 
so use the above dmd lines


Thanks for your help, Adam!  Right after posting my question, I 
started reading this site:

https://www.tutorialspoint.com/d_programming/d_programming_modules.htm

Based on that and your recommendation, here is what I ended up 
doing:
I changed the filename of isPrime.d to isprime.d and put that in 
the subdirectory func/:


func/isprime.d:
module func.isprime;
bool isPrime(int n) {
// check to see if n is prime
}

I then changed main.d to:
import func.isprime;
void main() {
isPrime(x);
}

Finally, per your suggestion, I compiled it using:
dmd -i main.d

Thanks again!


Re: "Error: function expected before (), not module *module* of type void

2018-09-21 Thread Samir via Digitalmars-d-learn
On Monday, 24 March 2008 at 17:41:11 UTC, Steven Schveighoffer 
wrote:
I know you fixed the problem, but just an FYI, the reason is 
because when you import rollDice, you bring both rollDice the 
module and rollDice the function into the global namespace 
(which confuses the compiler 'cause it doesn't know what symbol 
you want to use).  This is normally avoided in libraries by 
having a package tree.  So for example, if you created 
everything in the subdirectory foo, and had your modules be:


module foo.diceroller;
import foo.rollDice;

Then the import would import the module foo.rollDice, and the 
function rollDice, and the compiler would no longer be confused 
about what you are trying to call.


IMO, this makes it difficult to write multi-file applications 
that live in one directory.  It would be nice if this was 
changed...


-Steve


I know this thread is quite old but I still seem to be getting a 
similar error and don't understand how to resolve it. I currently 
have a program isPrime.d that I would like to reuse in other 
programs:


isPrime.d:
bool isPrime(int n) {
// logic to check if n is prime
}

main.d:
import isPrime;
void main() {
isPrime(x);
}

Both files are in the same directory. When compiling main.d, I 
get:
Error: function expected before (), not module isPrime of type 
void


I've tried changing the name of the function isPrime in isPrime.d 
to something else (as well as changing the name in the main 
program) but then I get an error similar to:

In function `_Dmain':
main.d:(.text._Dmain[_Dmain]+0x83): undefined reference to 
`_D7isPrime3isPFiZb'

collect2: error: ld returned 1 exit status
Error: linker exited with status 1

Thanks in advance.