Re: task can't take a class method

2018-11-19 Thread helxi via Digitalmars-d-learn

On Monday, 19 November 2018 at 17:18:14 UTC, John Chapman wrote:

1) task()


Thanks, that helped.




Re: task can't take a class method

2018-11-19 Thread helxi via Digitalmars-d-learn

On Monday, 19 November 2018 at 16:10:15 UTC, helxi wrote:

...


Oh wait never mind I was missing a bracket:

auto proc = task!(ddCall.dd());

Now I have another thing to worry about: ddcall.dd() cannot be 
read at compile time.






task can't take a class method

2018-11-19 Thread helxi via Digitalmars-d-learn

I want to create a task out of an object's method. My Class is:

public class Calldd
{
private:
const string tmpFileName = "/tmp/nixwriter.progress.txt";
string deviceName, sourceFileName;

public:
this(in string sourceFileName, in string deviceName)
{
this.sourceFileName = sourceFileName;
this.deviceName = deviceName;
}

int dd()
{
static ddcount = 0;
++ddcount;
scope (success)
--ddcount;
if (ddcount > 1)
return 1;
// Running dd again should be made impossible by the user 
from the UI level

// I'm not making the code any more complicated

import std.format : format;

immutable string command = format("pkexec dd if=/%s of=%s 
bs=4M status=progress 2>%s && sync",

sourceFileName, deviceName, tmpFileName);

return executeShell(command).status;
}

double parse()
{
import std.file : readText, getSize;
import std.string : splitLines, isNumeric;
import std.range : front, back, split;
import std.conv : to;

try
{
if (!(tmpFileName.exists))
return 0;
auto text = tmpFileName.readText();
if (text.splitLines().length == 0)
return 0;
if 
(text.splitLines().back().split().front().isNumeric())

return text.splitLines().back().split().front()
.to!double * 100 / (getSize(sourceFileName));
}
catch (Exception e)
{
// Sanitize exceptions
}
return 0;
}

~this()
{
import std.file : exists, remove;

if (tmpFileName.exists())
remove(tmpFileName);
}

}

My call site:

trigger.addOnClicked(delegate void(Button _) {
// ...
auto sourceFileName = fcb.getFilename(),
deviceName = 
parseDeviceName(deviceCombo.getActiveText());


auto ddCall = new Calldd(sourceFileName, deviceName);
import std.parallelism : task;

auto proc = task!ddCall.dd(); // <-- compilation 
failure

proc.executeInNewThread();

});


The compiler says:
$ dub build
Performing "debug" build using /usr/bin/dmd for x86_64.
gtk-d:gtkd 3.8.3: target for configuration "library" is up to 
date.

nixwriter ~master: building configuration "application"...
/usr/include/dlang/dmd/std/parallelism.d(507,34): Error: no 
property opCall for type backend.Calldd, did you mean new Calldd?
/usr/include/dlang/dmd/std/parallelism.d(835,16): Error: template 
instance `ui.PrimaryWindow.this.__dgliteral4.Task!(ddCall)` error 
instantiating

source/ui.d(200,25):instantiated from here: task!(ddCall)
/usr/bin/dmd failed with exit code 1.

I gather that I have to define an OpCall for this. I thought 
about calling the constructor inside the OpCall. But the ctor 
needs two values itself. However the OpCall is being called 
implicitly(?) somewhere. How can I get around this?

Note that the method dd() itself takes no params.


Re: Reading into the output of a long running shellExecute

2018-11-12 Thread helxi via Digitalmars-d-learn

On Saturday, 10 November 2018 at 15:54:07 UTC, JN wrote:

On Saturday, 10 November 2018 at 15:05:38 UTC, helxi wrote:
Hi. I have not done any multi-threaded programming before. 
What I basically want is to read into the output of a long 
shellExecute function each second.


In details, I am calling shellExecute("pkexec dd 
if=/path/to/file of=/dev/sdx status=progress && sync");
It's a long running process and dd command prints how many 
bytes it has written in stdout continuously. I want to read 
and parse this output each second. How should I proceed?


shellExecute won't work, because it waits for the process to 
end before moving on.


I believe https://dlang.org/phobos/std_process.html#pipeProcess 
should do what you want. It returns a ProcessPipes object which 
has stdout, from which you should be able to read.


Okay I looked it up but now I have another question

 1  import std.process;
 2  import std.stdio;
 3  import std.range;
 4  import std.string;
 5  
 6	//pkexec dd 
if=/run/media/user1101/portable_drive/software/os/manjaro-kde-18.0-stable-x86_64.iso of=/dev/sdd bs=4M status=progress 2>&1 && sync

 7  
 8  void main() {
 9	auto pipe = pipeShell("bash", Redirect.stdout | 
Redirect.stderr | Redirect.stdin);

10  pipe.stdin.writeln(
11	"pkexec dd 
if=/run/media/user1101/portable_drive/software/os/manjaro-kde-18.0-stable-x86_64.iso of=/dev/sdd bs=4M status=progress 2>&1 && sync"

12  );
13  pipe.stdin.flush();
14  pipe.stdin.close();
15  
16  foreach (line; pipe.stdout.byLineCopy)
17  foreach (word; line.split)
18  writeln(word);
19  }

What I want is to instantly print whatever dd prints to the 
stdout. (I made dd to redirect output to stdout with 2>&1 
already). But the problem is, the pipe waits until dd finishes 
writing to stdout. How can I make the pipe not wait for dd to 
finish?


}




Re: How does calling function pointers work?

2018-11-12 Thread helxi via Digitalmars-d-learn
On Monday, 12 November 2018 at 16:25:13 UTC, Rene Zwanenburg 
wrote:
Idk where you got that syntax from, but there's no syntactic 
difference between calling normal functions and function 
pointers:


import std.stdio;
import std.concurrency;
import core.thread;

void worker(int firstNumber) {
foreach (i; 0 .. 4) {
Thread.sleep(500.msecs);
writeln(firstNumber + i);
}
}

void main() {
foreach (i; 1 .. 3) {
spawn(, i * 10);
}
}


Looks like worker needs an int and spawn(, i * 10) seems 
to feed it's second arg to worker(?)


Re: How does calling function pointers work?

2018-11-12 Thread helxi via Digitalmars-d-learn

On Monday, 12 November 2018 at 16:08:28 UTC, helxi wrote:

Line 12 was meant to print 1234.
Line 13 was meant to print 1234 too, but for a different reason.


Correction, it was meant to print 12304. My bad.



How does calling function pointers work?

2018-11-12 Thread helxi via Digitalmars-d-learn
As far as I understand, calling a function pointer with an 
argument in D looks like:


call(, argTofn0, argTofn1, argTofn3);

This immediately struck me a very weak syntax to me so I decided 
to explore my concerns.
I made a function pointer that takes an indefinite number of 
arguments.


 1  import std.stdio;
 2
 3  int total(int[] numbers ...) {
 4  int result;
 5  for(ulong i = 0; i < numbers.length; result += 
numbers[i++]){}

 6  return result;
 7  }
 8
 9
10  void main() {
11  writeln(total(1000, 200, 30, 4)); // 1234
12  writeln(, 1000, 200, 30, 4); // 
55CA386877AC1000200304

13  writeln((, 1000, 200, 30), 4); // error lmao
14  }

How do you guys make writeln distinguish between an arg meant for 
writeln from an arg meant for ?

FYI
Line 12 was meant to print 1234.
Line 13 was meant to print 1234 too, but for a different reason.


Reading into the output of a long running shellExecute

2018-11-10 Thread helxi via Digitalmars-d-learn
Hi. I have not done any multi-threaded programming before. What I 
basically want is to read into the output of a long shellExecute 
function each second.


In details, I am calling shellExecute("pkexec dd if=/path/to/file 
of=/dev/sdx status=progress && sync");
It's a long running process and dd command prints how many bytes 
it has written in stdout continuously. I want to read and parse 
this output each second. How should I proceed?


Re: Exception slipping through the catch block?

2018-11-08 Thread helxi via Digitalmars-d-learn

On Thursday, 8 November 2018 at 15:41:11 UTC, Adam D. Ruppe wrote:

On Thursday, 8 November 2018 at 15:08:40 UTC, helxi wrote:

Shouldn't the catch block in the function catch the exception?


You caught Exception, but it throws Error. They have separate 
inheritance trees.



The common ancestor is actually Throwable, though note that 
there is no guarantee that Errors actually unwind the stack; 
with certain compile flags they might just abort the program.


Thanks.

Although it's pretty frustrating, isn't it? Now not only I have 
to think about catching exceptions but also about Errors, and 
have no guarantee that I have everything under control.


Exception slipping through the catch block?

2018-11-08 Thread helxi via Digitalmars-d-learn
How does exception work? I am inside a function that calls a 
constructor. Inside the constructor, an exception is thrown. 
However even though I have wrapped the body of the function 
inside a try/catch block, the program crashes from inside that 
constructor. Shouldn't the catch block in the function catch the 
exception?


Picture should clear it up a little bit:
https://i.imgur.com/3zinoZq.png

   // ui.d
   103	deviceCombo.addOnChanged(delegate 
void(ComboBoxText _) {

   104  try {
   105	device = new 
Device(deviceCombo.getActiveText()); // <-- call sight
   106	auto status = sanityCheck(device, 
fcb.getFilename);

   107  if (status.pass)
   108	
triggerHboxRevealer.setRevealChild(true);

   109  else {
   110	
deviceCombo.setTooltipText(status.reason);
   111	
triggerHboxRevealer.setRevealChild(false);

   112  }
   113  }
   114  catch (Exception e) {
   115	deviceCombo.setTooltipText("Cannot read 
device");

   116  triggerHboxRevealer.setRevealChild(false);
   117  }
   118  });


// backend.d
34  this(in string lsblkLine) {
35  auto lineSplit = lsblkLine.split(" ");
36  name = lineSplit.front();
37  sizePretty = lineSplit.back();
38	foreach (str; lineSplit.dropOne().dropBackOne()) 
// <-- throws exception

39  model ~= str ~ " ";
40	summary = format("%s\t%s\t%s", name, model, 
sizePretty);

41  }

// error message
core.exception.AssertError@/usr/include/dlang/dmd/std/range/primitives.d(2340): 
Assertion failure

??:? _d_assertp [0x4e81ee29]
/usr/include/dlang/dmd/std/range/primitives.d:2340 pure nothrow 
@nogc @safe void 
std.range.primitives.popBack!(immutable(char)[]).popBack(ref 
immutable(char)[][]) [0x4e5e417e]
/usr/include/dlang/dmd/std/range/package.d:3190 pure nothrow 
@nogc @safe immutable(char)[][] 
std.range.dropBackOne!(immutable(char)[][]).dropBackOne(immutable(char)[][]) [0x4e5e41d4]
source/backend.d:38 backend.Device 
backend.Device.__ctor(const(immutable(char)[])) [0x4e5e8e6d]
source/ui.d:105 void 
ui.PrimaryWindow.__ctor(gtk.Application.Application).__dgliteral4(gtk.ComboBoxText.ComboBoxText) [0x4e5ea17f]

../../../../.dub/packages/gtk-d-3.8.3/gtk-d/generated/gtkd/gobject/DClosure.d:135
 extern (C) void gobject.DClosure.DClosure.d_closure_marshal!(void 
delegate(gtk.ComboBoxText.ComboBoxText)).d_closure_marshal(gobject.c.types.GClosure*,
 gobject.c.types.GValue*, uint, gobject.c.types.GValue*, void*, void*) 
[0x4e7bf095]
??:? g_closure_invoke [0x4f9573d4]
Program exited with code 1


Re: Where do I learn to use GtkD

2018-10-31 Thread helxi via Digitalmars-d-learn

On Tuesday, 30 October 2018 at 14:38:53 UTC, Michelle Long wrote:

On Sunday, 13 March 2016 at 19:28:57 UTC, karabuta wrote:
Gtk3 from python3 has got I nice book with examples that are 
not so advanced but enough to get you doing real work(from a 
beginner point of view). GtkD seem to have changed the API 
structure compared to python3 Gtk3 and the demo examples just 
"show-off" IMO :). The documentation is really^ not good :)


Any help on where I can get better leaning materials(GtkD)? 
Repo, blogs post, etc please


I will avoid using GTK for large projects. If can be used for 
simple things and you can automate a lot of acts(and use glade 
for UI design)... but it has some problems that will bite you 
in the long run.


Why is that, if I may ask? Is it the licensing concerns?

I'd just jump in to it, it's not too hard but hard to find the 
correct information. It will be a time investment of a few 
months.


Might try nuklearD first. Seems to be better in many aspects.


I believe the gtk stack is very comprehensive. It integrates to 
Linux desktops fairly well. Has nice power management rules, 
support for appID, and many widgets.


Re: Where do I learn to use GtkD

2018-10-29 Thread helxi via Digitalmars-d-learn

On Sunday, 13 March 2016 at 19:28:57 UTC, karabuta wrote:
Gtk3 from python3 has got I nice book with examples that are 
not so advanced but enough to get you doing real work(from a 
beginner point of view). GtkD seem to have changed the API 
structure compared to python3 Gtk3 and the demo examples just 
"show-off" IMO :). The documentation is really^ not good :)


Any help on where I can get better leaning materials(GtkD)? 
Repo, blogs post, etc please


Sorry for the shameless self plug, and I know it's already too 
late. I have been working on porting some of the pygtk examples 
to GtkD and covered almost the half of it. For anyone who is 
reading this thread please check out the repo I mention bellow. 
For experienced users of GtkD, please leave your PRs and 
suggestions.



https://gitlab.com/9898287/gtkdnotes



Re: Prevent opening binary/other garbage files

2018-10-01 Thread helxi via Digitalmars-d-learn

On Sunday, 30 September 2018 at 03:19:11 UTC, Adam D. Ruppe wrote:

On Saturday, 29 September 2018 at 23:46:26 UTC, helxi wrote:
Thanks. Would you say 
https://dlang.org/library/std/encoding/get_bom.html is useful 
in this context?


Eh, not really, most text files will not have one.


Hi,

I tried out https://dlang.org/library/std/utf/validate.html 
before manually checking for encoding myself so I ended up with 
the code below. I was fairly surprised that "*.o" (object) files 
are UTF encoded! Is it normal?


import std.stdio : File, lines, stdout;

void panic(in string message, int exitCode = 1) {
import core.stdc.stdlib : exit;
import std.stdio : stderr, writeln;

stderr.writeln(message);
exit(exitCode);
}

void writeFunc(ulong occerenceNumber, ulong lineNumber, in ref 
string fileName,

in ref string line, File ofile = stdout) {
import std.stdio : writef;

	ofile.writef("%s: L:%s: F:\"%s\":\n%s\n", occerenceNumber, 
lineNumber, fileName, line);

}

void treverseDirectories(in string path, in string term)
in {
import std.file : isDir;

if (!isDir(path))
panic("Cannot access directory: " ~ path);
}
do {
import std.file : dirEntries, SpanMode;

ulong occerenceNumber, filesChecked, filesIgnored; // = 0;
File currentFile;
foreach (string fileName; dirEntries(path, SpanMode.breadth)) {
try {
currentFile = File(fileName, "r");
++filesChecked;
			foreach (ulong lineNumber, string currentLine; 
lines(currentFile)) {

if (lineNumber == 0) {
// check if the file is encoded with 
proper UTF
// if Line 0 is not UTF encoded, move 
on to the next file

// I hope the compiler unrolls this if 
condition
import std.utf : validate;

validate(currentLine);
// throws exception if 
the file is not UTF encoded

}
import std.algorithm : canFind;

if (canFind(currentLine, term)) {
	writeFunc(++occerenceNumber, lineNumber, fileName, 
currentLine);

}
}
}
catch (Exception e) {
filesIgnored++;
}
}
//summarize
import std.stdio : writefln;

	writefln("Total match found:\t%s\nTotal files 
checked:\t%s\nTotal files ignored:\t%s\n",

occerenceNumber, filesChecked, filesIgnored);
}

void main(string[] args) {
import std.getopt : getopt;

string term, directory;
getopt(args, "term|t", , "directory|d", );

if (!directory) {
		// if directory not specified, start working with the current 
directory

import std.file : getcwd;

directory = getcwd();
}

if (!term)
panic("Term not specified.");

treverseDirectories(directory, term);
}


/*

Output:  https://pastebin.com/PZ8nCaYf


Re: Prevent opening binary/other garbage files

2018-09-29 Thread helxi via Digitalmars-d-learn
On Saturday, 29 September 2018 at 16:01:18 UTC, Adam D. Ruppe 
wrote:

On Saturday, 29 September 2018 at 15:52:30 UTC, helxi wrote:
I'm writing a utility that checks for specific keyword(s) 
found in the files in a given directory recursively. What's 
the best strategy to avoid opening a bin file or some sort of 
garbage dump? Check encoding of the given file?


Simplest might be to read the first few bytes (like couple 
hundred probably) and if any of them are < 32 && != '\t' && != 
'\r' && != '\n' && != 0, there's a good chance it is a binary 
file.


Text files are frequently going to have tabs and newlines, but 
not so frequently other low bytes.


If you do find a bunch of 0's, but not the other values, you 
might have a utf-16 file.


Thanks. Would you say 
https://dlang.org/library/std/encoding/get_bom.html is useful in 
this context?


Prevent opening binary/other garbage files

2018-09-29 Thread helxi via Digitalmars-d-learn
I'm writing a utility that checks for specific keyword(s) found 
in the files in a given directory recursively. What's the best 
strategy to avoid opening a bin file or some sort of garbage 
dump? Check encoding of the given file?


If so, what are the most popular encodings (in POSIX if that 
matters) and how do I detect them?


Re: Is std.variant.visit not @nogc?

2018-04-09 Thread helxi via Digitalmars-d-learn

On Monday, 9 April 2018 at 15:59:32 UTC, Paul Backus wrote:

On Monday, 9 April 2018 at 07:07:58 UTC, Chris Katko wrote:

[...]


I agree in general, but in this case it's actually completely 
doable. In fact, I've done it myself: check out 'sumtype' on 
code.dlang.org. You can replace 'Algebraic' with 'SumType' and 
'visit' with 'match' in helxi's example, and everything Just 
Works™:


[...]


This isn't boxed by any chance, is it?


Is std.variant.visit not @nogc?

2018-04-08 Thread helxi via Digitalmars-d-learn

import std.variant, core.stdc.stdio;

Algebraic!(T, string) fib_nth(T)(T n)
{
return n % 15
? n % 5
? n % 3
? Algebraic!(T, string)(n)
: Algebraic!(T, string)("Fizz")
: Algebraic!(T, string)("Buzz")
: Algebraic!(T, string)("Fizzbuzz");
}

void main() @nogc
{
foreach (i; 1 .. 101)
{
fib_nth(i).visit!(
(string s) => printf("%s\n", s.ptr),
(int n) => printf("%i\n", n)
);
}
}


Complains source/app.d(18,19): Error: @nogc function D main 
cannot call non-@nogc function std.variant.visit!(function 
(string s) => printf("%s\x0a", cast(immutable(char)*)s), function 
(int n) => printf("%i\x0a", n)).visit!(VariantN!(16LU, int, 
string)).visit

/usr/bin/dmd failed with exit code 1.


If so, is there a way to emulate `visit` in a @nogc setting?


What is the equivalent of C++'s std::optional and std::nullopt in D?

2018-04-02 Thread helxi via Digitalmars-d-learn

For reference: https://en.cppreference.com/w/cpp/utility/optional





Re: Avoiding default generic types, and allocator awareness

2017-12-30 Thread helxi via Digitalmars-d-learn

On Saturday, 30 December 2017 at 15:00:32 UTC, helxi wrote:
As an exercise in http://ddili.org/ders/d.en/pointers.html, I 
was implementing a very stripped down version of singly linked 
list like below:

struct Node(T)
{
T item;
Node!T* next_item;
}

[...]


Correction, I meant:
If I leave the signature like

these, is it actually going to affect the structure in anyway?:
void push_front(T, N)(ref Forward_List!(T, N) list, T item);
string to_string(T, N)(ref Forward_List!(T, N) list);


Avoiding default generic types, and allocator awareness

2017-12-30 Thread helxi via Digitalmars-d-learn
As an exercise in http://ddili.org/ders/d.en/pointers.html, I was 
implementing a very stripped down version of singly linked list 
like below:

struct Node(T)
{
T item;
Node!T* next_item;
}

string to_string(T)(in Node!T node)
{
import std.format;
return node.nextItem ? "%s -> %s".format(node.item, 
*(node.nextItem))

 : "%s".format(node.item);

}

struct Forward_List(T, N = size_t)
{
Node!T* head;
N size;
}

string to_string(T, N = size_t)(ref Forward_List!(T, N) list)
{
//todo
import std.format;
return "head*: %s, size: %s)".format(, list.size);
}

void push_front(T, N = size_t)(ref Forward_List!(T, N) list, T 
item)

{
list.head = new Node!T(item, list.head);
++list.size;
}

1. If you have noticed, I am needlessly repeating `N = size_t` in 
to_string and push_front. If I leave the signature like these, is 
it actually going to affect the structure in anyway?:
void push_front(T, N = size_t)(ref Forward_List!(T, N) list, T 
item);

string to_string(T, N = size_t)(ref Forward_List!(T, N) list);

2. How does one make it "allocator aware"? What other allocators 
can I use?





Curiously Recurring Template Pattern Example

2017-12-25 Thread helxi via Digitalmars-d-learn
Hi, Is there any blogs that discuss CRTP, or even Policy 
based/introspection based design in idiomatic D?


I would love to see the strategies used to tackle the overhead 
involving dynamic dispatch by emulating static polymorphism.


Thanks.


Seperating class methods in a different module

2017-12-06 Thread helxi via Digitalmars-d-learn
1. How can I separate class methods from the declaration block? 
And how can I implement them in a separate module?


module frame;
class Test
{
public:
int x;
this();
}

Test.this()
{
x = 34;
} // does not work

In this scenario I would like to take the constructor to a 
different module called "construct".



2. For practice, I want to implement a few containers in native D 
using DUB. The project aims to create libraries for different 
data structures. I'm thinking that I should make packages for 
different containers and have them under source/. For example, 
source/forward_list, source/queue, source/set etc.


Would you like to suggest me a good project structures for this? 
Imagine I am making a package called forward_list. Under the 
directory forward_list/, I have modules.d that imports dedicated 
modules for useful methods like push_back, insert_after, front, 
sort, merge etc. Is it an acceptable practice to declare classes 
in package.d? So it becomes


//module package.d;
class forward_list
{
public:
int x;
merge();

this(){}
this(int x){ this.x = x; }
}

//module merge.d;
import package.d

forward_list.merge(Object o){
//..
}


Re: Optimizing a bigint fibonacci

2017-12-06 Thread helxi via Digitalmars-d-learn

On Wednesday, 6 December 2017 at 10:00:48 UTC, Biotronic wrote:

On Wednesday, 6 December 2017 at 09:12:08 UTC, helxi wrote:

[...]


Here's my version:, based on fast squaring:

auto fib(ulong n) {
import std.bigint : BigInt;
import std.meta : AliasSeq;
import std.typecons : tuple;
BigInt a = 0;
BigInt b = 1;
auto bit = 63;
while (bit > 0) {
AliasSeq!(a, b) = tuple(
a * (2*b - a),
a*a + b*b);

[...]


Nice. But why the AliasSeq?

That's because the poor compiler isn't as good at optimizing 
compile-time code as run-time code,


Oh I see. We should definitely be careful with that :D


Optimizing a bigint fibonacci

2017-12-06 Thread helxi via Digitalmars-d-learn
This is question not directly related to language concepts, it's 
got more to do with the application. I would appreciate if anyone 
would point to me how I could optimize this bit of code

auto fib(const int n)
{
import std.bigint;

if (n == 0)
return BigInt(0);

if (n == 1)
return BigInt(1);

BigInt next;
for (BigInt i = 0, j = 1, count = 1; count < n; ++count)
{
next = i + j;
i = j;
j = next;
}
return next;
}

void main()
{
import std.stdio, std.datetime;

auto t0 = Clock.currTime;
writeln(fib(100_000));
writeln(Clock.currTime - t0);
}



I also noticed that if I try to compute it in the compile time 
with enum x = fib(10) the compiler freezes. What could cause 
this?


Using enum types

2017-12-04 Thread helxi via Digitalmars-d-learn

Why can't enums be used as types in this (simplified) example?

enum Positivity
{
Positive,
Negative
}

struct Wave
{
public:
Positivity slope;
}

enum Waves
{
Sin = Wave(Positivity.Positive),
Cos = Wave(Positivity.Negative)
}

int nth_value(T : Waves)(int n);

int nth_value(T : Waves.Sin)(int n)
{
return n % 2 ? 1 : -1;
}

int nth_value(T : Waves.Cos)(int n)
{
return n % 2 ? -1 : 1;
}

void main()
{
import std.stdio;

writeln(nth_value!(Waves.Sin)(1));
}


Template specialisation, "Generic type locking", offline stdlib docs and case-based template question

2017-11-30 Thread helxi via Digitalmars-d-learn

1. Template specialisation.
Why is this useful?:
T getResponse(T = int)(string question); And how does it differ 
from

int getResponse(string question); ?

Context: http://ddili.org/ders/d.en/templates.html : Section: 
"Default template parameters"


2. "Generic locking".
Is it possible to specialise templates for a certain group of 
types? For example

auto fn(T)(T arg)
auto fn(T : int, double, float, ulong)(T arg); //shares same 
behaviour
auto fn(T : char, string, dchar, wchar, dstring, wstring)(T arg); 
// shares same behavior


3. "Offline docs".
Is there any offline documentation of the stdlib? Like 
https://en.cppreference.com/mwiki/index.php?title=Cppreference:Archives=95461


4. Case based question regarding templates:

class Stack(T)
{
private:
T[] data;
public:
this(T)(T[] data){ /*..*/}
this(T)(){}

   //...

}

void main()
{
auto s = new Stack!int;
}

Says:
 Error: template app.Stack!int.Stack.__ctor cannot deduce 
function from argument types !()(), candidates are:

source/app.d(6,2):app.Stack!int.Stack.__ctor(T)(T[] data)
source/app.d(9,2):app.Stack!int.Stack.__ctor(T)()

Why is Stack!int a ctor()() instead of a ctor(int)()?


Re: Private imports and Objects

2017-11-30 Thread helxi via Digitalmars-d-learn
On Thursday, 30 November 2017 at 06:44:43 UTC, Jonathan M Davis 
wrote:
On Thursday, November 30, 2017 06:29:43 helxi via 
Digitalmars-d-learn wrote:

[]
I don't understand the question. You're asking whether casting 
from a base class to a derived class creates overhead? Or are 
you asking whether having a base class for all classes creates 
overhead? Or something else?


Object exists primarily because D didn't originally have 
templates, and when you don't have templates, having a single 
base class is the only way to have a function accept any class, 
and for something like a container, you'd pretty much be forced 
to use void* without Object if you don't have templates. 
However, once templates were added to D, the benefits of Object 
were significantly reduced, and it's arguably not a 
particularly good idea to be writing code that operates on 
Object. However, it's far too late in the game to get rid of 
Object.


At one point, it was decided to remove Object's member 
functions, because having them on Object needlessly locks in a 
particular set of attributes for those functions, and if we did 
that, then there really wouldn't be much reason to use Object 
directly, but that change has never happened, and it's not 
clear that it's going to happen, since there are a number of 
technical issues that make it a bit of a pain to do 
(particularly if we don't want to break a lot of code). One of 
the bigger issues is that the AA implementation in druntime 
needs to be templated so that it doesn't need to operate on 
Object, and that's proven to be a bit of a challenge.


https://issues.dlang.org/show_bug.cgi?id=9769 
https://issues.dlang.org/show_bug.cgi?id=9770 
https://issues.dlang.org/show_bug.cgi?id=9771 
https://issues.dlang.org/show_bug.cgi?id=9772


- Jonathan M Davis


I was actually referring to both. Override functions such as 
opCmp, opEquals, toString, toHash etc --wouldn't they be 
inherently expensive? I thought they are virtual functions. Also, 
with regards to casting, wouldn't this be an extra legwork? Both 
of these seem to be a performance handicap to me. But I'm no 
expert on this matter. Maybe the compiler optimises it away since 
normally you'd cast to a constant subclass.


Private imports and Objects

2017-11-29 Thread helxi via Digitalmars-d-learn
1. Why are imports visible from outside the package when you do 
selective imports?


//mod.d
module mod;

import std.stdio : writeln;

public void greet()
{
writeln("Hello");
}


//app.d
import mod;

void main()
{
mod.greet();
writeln("You should not be seeing this.");

}

Compiles just fine and prints "You should not be seeing this." 
just fine with `$dub build`. Even if I use package imports the 
result stays the same.


2. Classes that do not inherit (base classes) actually inherit 
from 'Object`. For which, often times one converts the Object to 
its subclasses. What's the rationale behind this?

Isn't this going to add overhead?




Re: Taking a constant reference to a constant/non const object

2017-11-15 Thread helxi via Digitalmars-d-learn

On Wednesday, 15 November 2017 at 09:34:32 UTC, helxi wrote:
On Wednesday, 15 November 2017 at 09:23:53 UTC, Jonathan M 
Davis wrote:
On Wednesday, November 15, 2017 09:04:50 helxi via 
Digitalmars-d-learn wrote:
Hi. What function signature should I use for receiving a 
constant
reference of an r/l value object? Is it auto fn(inout ref 
const

myClass obj)?
I want to:
1. Take a constant reference of the object, not copy them
2. The object itself may be const or non const.


ref const(Type) would be the const version of ref Type. e.g.

auto foo(ref const(int) i) {...}

- Jonathan M Davis


Thanks. Just a couple of follow-ups:
1. I've never seen a signature like `const(int)`is the 
enclosing parenthesis around the `int` necessary?
2. What effects does prefixing the arguments with `inout` have? 
For example:  fn(inout ref const string str){...}


Terribly sorry for my bad choice of words. Basically I want to 
utilize D's "inout" to avoid writing two functions like this:


#include 
#include 

void fn(std::string& str) {
  std::cout << str << " called from fn(std::string& str)"
<< "\n ";
}

void fn(const std::string& str) {
  std::cout << str << " alled from fn(const std::string& str)"
<< "\n";
}

int main() {
  fn("Test 1");
  std::string b = "test";
  b += " 2";
  fn(b);
}



Re: Taking a constant reference to a constant/non const object

2017-11-15 Thread helxi via Digitalmars-d-learn
On Wednesday, 15 November 2017 at 09:23:53 UTC, Jonathan M Davis 
wrote:
On Wednesday, November 15, 2017 09:04:50 helxi via 
Digitalmars-d-learn wrote:
Hi. What function signature should I use for receiving a 
constant

reference of an r/l value object? Is it auto fn(inout ref const
myClass obj)?
I want to:
1. Take a constant reference of the object, not copy them
2. The object itself may be const or non const.


ref const(Type) would be the const version of ref Type. e.g.

auto foo(ref const(int) i) {...}

- Jonathan M Davis


Thanks. Just a couple of follow-ups:
1. I've never seen a signature like `const(int)`is the enclosing 
parenthesis around the `int` necessary?
2. What effects does prefixing the arguments with `inout` have? 
For example:  fn(inout ref const string str){...}


Taking a constant reference to a constant/non const object

2017-11-15 Thread helxi via Digitalmars-d-learn
Hi. What function signature should I use for receiving a constant 
reference of an r/l value object? Is it auto fn(inout ref const 
myClass obj)?

I want to:
1. Take a constant reference of the object, not copy them
2. The object itself may be const or non const.


opCast'ing strings

2017-11-12 Thread helxi via Digitalmars-d-learn

struct Fraction
{
private:
int numerator = 1, denominator = 1;
public:
string opCast(T : string)() const
{
import std.conv : to;

return numerator.to!string() ~ "/" ~ denominator.to!string();
}
}

void main()
{
import std.stdio, std.conv;

Fraction n = Fraction(23, 11);
writeln(n.to!string(), " ", n.opCast!string);
}



In this program, casting using to does not work as intended 
(returning 23/11) on the struct. However, calling opCast directly 
seems to do the job. Why is that?


Can't get expected strings

2017-07-18 Thread helxi via Digitalmars-d-learn

import std.stdio, std.datetime, std.conv, std.algorithm;

void main()
{
immutable DEADLINE = DateTime(2017, 7, 16, 23, 59, 
59).to!SysTime;

immutable NOW = Clock.currTime;
immutable INTERVAL = (DEADLINE - NOW)
.abs
.to!string;
//if I put .until("secs") here, it prints 
the full-type
//immutable(Until!("a == b", string, 
string))("1 day, 23 hours, 47 minutes, 30 secs, 508 ms, 119 μs, 
and 6 hnsecs", "secs", yes, false)



writeln(INTERVAL);

//But I don't want these until("secs") below:
if (NOW > DEADLINE) writeln(INTERVAL.until("secs"), "seconds 
ago.");

//1 day, 23 hours, 48 minutes, 55 seconds ago.
else if (NOW < DEADLINE) writeln(INTERVAL.until("secs"), 
"seconds ahead.");

else writeln("Now.");
}

-


Why is to!string providing inconsistent string?


Re: [BEGINNER] reccurence! and sequence!

2017-07-06 Thread helxi via Digitalmars-d-learn

On Thursday, 6 July 2017 at 00:21:44 UTC, Ali Çehreli wrote:

On 07/05/2017 04:38 PM, helxi wrote:

>> [...]
>
> Oh thank you. Just 2 follow-up questions:
>> [...]
> 1. In the last example of reccurence, what does n in (a,n)
refer to?

n is "the index of the current value". Each time the lambda is 
called,


  a[n] is what is being generated
  a[n-1] is the previous value
  a[0] is the same as a[n-1]? (I find this confusing)

> 2. How would you chain until! with reccurence? For example I
want to
> compute 1, 10, 100, ..., (until the value remains smaller
than 1000_000)?

import std.stdio;
import std.algorithm;
import std.range;

void main() {
auto r = recurrence!((a, n) => a[n-1] * 10)(1);
auto u = r.until!(a => a >= 1_000_000);
writeln(u);
}

[1, 10, 100, 1000, 1, 10]

Ali


Hmm, I get it now. Thank you very much.


Re: [BEGINNER] reccurence! and sequence!

2017-07-05 Thread helxi via Digitalmars-d-learn

On Monday, 26 June 2017 at 10:34:22 UTC, ag0aep6g wrote:

On 06/26/2017 11:51 AM, helxi wrote:

[...]


`a` is a tuple of the run-time arguments you pass to 
`sequence`. In this example, no arguments are passed (empty 
parens at the end of the call), so `a` is empty.



[...]


a[0] = 1
a[1] = 2


[...]


`a` isn't used in the string lambda, and it's not considered an 
element of the range. So n starts at 0 and this just prints 
0+2, 1+2, 2+2, etc.



[...]


`a` is still not used in the string lambda, but `recurrence` 
uses the values in `a` as the first elements of the range. `n` 
is incremented accordingly (to 1), so this prints:


1 = a[0],
3 = (n = 1) + 2,
4 = (n = 2) + 2,
etc.

Another difference between `sequence` and `recurrence` is that 
`a` always refers to the same initial value(s) in `sequence`, 
while in `recurrence` it gets updated and refers to the 
previous element(s) of the range:



sequence!((a, n) => a[0] + 1)(1).take(10).writeln;
// [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
// because a[0] is always 1

recurrence!((a, n) => a[0] + 1)(1).take(10).writeln;
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// because a[0] refers to the previous value



Oh thank you. Just 2 follow-up questions:

recurrence!((a, n) => a[0] + 1)(1).take(10).writeln;
1. In the last example of reccurence, what does n in (a,n) refer 
to?
2. How would you chain until! with reccurence? For example I want 
to compute 1, 10, 100, ..., (until the value remains smaller than 
1000_000)?


[BEGINNER] reccurence! and sequence!

2017-06-26 Thread helxi via Digitalmars-d-learn
Can someone give me a very watered-down explanation of what 
std.range's recurrence! and sequence! do?



auto tri = sequence!((a,n) => n*(n+1)/2)();


/** okay, it's a triangular number array
* I understand n is the index number, the nth term
* However where does this 'a' go?
*/


auto odds = sequence!("a[0] + n * a[1]")(1, 2);


/** okay, this is a range of odd numbers
/ where and how do I plug (1, 2) into ""a[0] + n * a[1]"


sequence!("n+2")(1).take(10).writeln;

//[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

recurrence!("n+2")(1).take(10).writeln;

//[1, 3, 4, 5, 6, 7, 8, 9, 10, 11]



O(1) sum

2017-06-11 Thread helxi via Digitalmars-d-learn

Is it possible to sum an array in O(1)?


Re: byLine(n)?

2017-06-11 Thread helxi via Digitalmars-d-learn

On Sunday, 11 June 2017 at 12:49:51 UTC, Cym13 wrote:
print each line


byLine doesn't reall all input at once. Using byline and take 
you are effectively reading only the right amount of lines and 
not reading the rest. You already have what you want, what 
makes you think the contrary?


Oh it was my lack of understanding then. Thank you. I would also 
be really humbled if you demonstrate a faster approach of 
achieving the goal of the program :) (without explicitly using 
loops and conditions)


Re: byLine(n)?

2017-06-11 Thread helxi via Digitalmars-d-learn

On Sunday, 11 June 2017 at 06:28:18 UTC, Stanislav Blinov wrote:

On Sunday, 11 June 2017 at 05:36:08 UTC, helxi wrote:
I was writing a program that reads and prints the first nth 
lines to the stdout:


import std.stdio;

void main(string[] args)
{
import std.algorithm, std.range;
import std.conv;
stdin.byLine.take(args[1].to!ulong).each!writeln;
}

As far as I understand the stdin.byLine.take(args[1].to!ulong) 
part reads all the lines written in stdin.
What if I want to make byLine read only and only first nth 
line?


stdin.byLine(args[1].to!ulong).each!writeln;

Obviously the code above won't work. Is there any efficient 
workaround?


You need only the nth line? Then you'd need to `drop` the 
preceding ones:


void main(string[] args) {
import std.algorithm, std.range, std.stdio, std.conv;
stdin.byLine.drop(args[1].to!int-1).front.writeln;
}

Or if you need every nth line, combine `drop` and `stride`:

void main(string[] args) {
import std.algorithm, std.range, std.stdio, std.conv;
auto step = args[1].to!int;
stdin.byLine.drop(step-1).stride(step).each!writeln;
}


I was actually just looking for ways to read the first n line and 
then print it ($man head). My current program

1. reads all the lines provided by the stdin (bottleneck)
2. takes the first n lines (bottleneck)
3. prints each line


I want to
1. read all the lines
2. when line number n is reached, stop reading the rest of the 
input

3. print each line


byLine(n)?

2017-06-10 Thread helxi via Digitalmars-d-learn
I was writing a program that reads and prints the first nth lines 
to the stdout:


import std.stdio;

void main(string[] args)
{
import std.algorithm, std.range;
import std.conv;
stdin.byLine.take(args[1].to!ulong).each!writeln;
}

As far as I understand the stdin.byLine.take(args[1].to!ulong) 
part reads all the lines written in stdin.

What if I want to make byLine read only and only first nth line?

stdin.byLine(args[1].to!ulong).each!writeln;

Obviously the code above won't work. Is there any efficient 
workaround?


Re: Input interrupt

2017-05-28 Thread helxi via Digitalmars-d-learn

On Sunday, 28 May 2017 at 22:14:46 UTC, Adam D. Ruppe wrote:

On Sunday, 28 May 2017 at 22:07:12 UTC, helxi wrote:
So I tried using C's EOF but the types aren't compatible since 
EOF is probably aliased to -1



The readln docs for D say it returns null on end of file. The 
example given is:


import std.stdio;

void main()
{
string line;
while ((line = readln()) !is null)
write(line);
}

http://dpldocs.info/experimental-docs/std.stdio.readln.1.html

I would try that.


Oh yes, fantastic,
I also seem to have forgotten EOF was meant to compare chars, not 
strings.


Input interrupt

2017-05-28 Thread helxi via Digitalmars-d-learn
Hello, I just wrote a mock-up of Unix's $cat. However unlike the 
actual $cat, when input interrupt (Cntrl+D) is pressed the 
following program does not stop.


So I tried using C's EOF but the types aren't compatible since 
EOF is probably aliased to -1


//...
if (args.length < 2)
{
string input = readln();
while (input != EOF)
{
input.write();
}
}
//...


Tips?



Here is the full program:



import std.stdio;
import std.file;

void main(string[] args)
{
if (args.length < 2)
{
string input = readln();
while (input != EOF)
{
input.write();
}
}
else
{
foreach (path; args[1..$])
{
auto current_file = File(path, "r");
while (!(current_file.eof()))
{
current_file.readln().write();
}
current_file.close();
}
}
}



foreach, is and pointer

2017-03-26 Thread helxi via Digitalmars-d-learn

What's the difference between
1.
string x = "abcd";
foreach(character; x)
write(character);

and

string x = "abcd";
foreach(character; x[0..$])
write(character);

2. is and ==

3. pointer and address and reference?


Sorting Assosiative Arrays and Finding Largest Common Substring

2017-03-16 Thread helxi via Digitalmars-d-learn
I was looking for ways to find the largest common substring 
between two given substrings and have learnt

1. .length is of type ulong
2. writing string[int] will not give me a sorted array
3. ulong cannot be sorted by sorted

What's the trick to sort the associative array by their keys?

Code snippet:


import std.stdio;

//find the largest substring of the two strings
void main(string[] args){

string str1 = args[1];
string str2 = args[2];

string[ulong] commons;

//is a char from str1[n] == str2[n]?
//is the char from str1[n+1] == str2[n+1]?

for (int i = 0; i < str1.length; i++){
for (int j = 0; j < str2.length; j++){
if (str2[j] == str1[i]){
string current = ""~str1[i];
for (int a = 1; (a+i < str1.length && a+j < 
str2.length); a++){

if(str2[a+j] == str1[a+i]){
current ~= str1[a+i];
}
}
commons[current.length] = current;
}
}
}
writeln(commons); //[4:"asdf", 2:"df", 1:"f", 3:"sdf"]
//writeln(commons[commons.keys.max]); <-won't work, no max 
for ulong[]

writeln(commons[commons.keys[0]]); //asdf
//but can't guarantee the largest value is the first key
}

---
$./main asdf asdfasdfc
[4:"asdf", 2:"df", 1:"f", 3:"sdf"]




Re: Best ways to declare associative arrays

2017-03-12 Thread helxi via Digitalmars-d-learn

On Sunday, 12 March 2017 at 07:58:40 UTC, helxi wrote:

return def;

I meant
return arg_array;


Best ways to declare associative arrays

2017-03-12 Thread helxi via Digitalmars-d-learn
How would an experienced programmer declare an associative array 
of strings that has 2 keys?


My initial impression was string[string][2] my_array; which does 
not seem to work.


Here is a snippet of the code I am working on:


import std.string;
import std.stdio;


string[string] change(ref string[string] arg_array){
//..
arg_array["first"] = strip(readln());
//..
arg_array["second"] = strip(readln());
//..
return def;
}

void main(){
string[string][2] test;
change(string[string] test);
}



Re: [Beginner]Variable length arrays

2017-02-25 Thread helxi via Digitalmars-d-learn
On Saturday, 25 February 2017 at 14:34:31 UTC, rikki cattermole 
wrote:

On 26/02/2017 3:31 AM, helxi wrote:
I am trying to create an array which has a user defined size. 
However

the following program is not compiling:

import std.stdio;

void main(){
write("Enter your array size: ");
int n;
readf(" %s", );
int[n] arr; //<-Error: variable input cannot be read at 
compile time

writeln(arr);
}

1. What's causing this?


T[X] is a static array, its size must be known at compile time.
Static arrays are passed around by value not by reference and 
generally get stored on the stack not the heap.


2. How can I get around this? I know I can always create a 
loop that

appends value 'n' times.


This is where you want a dynamic array, allocated on the heap 
at runtime.


T[] array;
array.length = n;


Thanks


[Beginner]Variable length arrays

2017-02-25 Thread helxi via Digitalmars-d-learn
I am trying to create an array which has a user defined size. 
However the following program is not compiling:


import std.stdio;

void main(){
write("Enter your array size: ");
int n;
readf(" %s", );
int[n] arr; //<-Error: variable input cannot be read at 
compile time

writeln(arr);
}

1. What's causing this?
2. How can I get around this? I know I can always create a loop 
that appends value 'n' times.