Re: Getting template parameters by its name

2019-01-11 Thread Yui Hosaka via Digitalmars-d-learn

On Friday, 11 January 2019 at 06:13:11 UTC, Paul Backus wrote:

On Friday, 11 January 2019 at 04:59:50 UTC, Yui Hosaka wrote:

I want to do something like this:


template S(T) {
}

void main() {
  pragma(msg, S!(int).T);  // Error: no property `T` for type 
`void`

}



You can get the arguments of a template instance as an AliasSeq 
using `std.traits.TemplateArgsOf`.


https://dlang.org/phobos/std_traits.html#TemplateArgsOf


It seems a good choice to me. Thank you!


Re: UTFException when reading a file

2019-01-11 Thread Dennis via Digitalmars-d-learn

On Friday, 11 January 2019 at 19:45:05 UTC, Head Scratcher wrote:
How can I read the file and convert the string into proper 
UTF-8 in memory without an exception?


You have multiple options:

```
import std.file: read;
import std.encoding: transcode, Windows1252String;
auto ansiStr = cast(Windows1252String) read(filename);
string utf8string;
transcode(ansiStr, utf8string);
```

If it's ANSI.

```
import std.encoding: sanitize;
auto sanitized =  (cast(string) read(filename)).sanitize;
```

If it's incorrect UTF8, eager

```
import std.exception: handle;
import std.range;
auto handled = str.handle!(UTFException, RangePrimitive.access,
(e, r) => ' '); // Replace invalid code points with spaces
```

If it's incorrect UTF8, lazy

See:
https://dlang.org/phobos/std_encoding.html#transcode
https://dlang.org/phobos/std_exception.html#handle


Re: UTFException when reading a file

2019-01-11 Thread H. S. Teoh via Digitalmars-d-learn
On Fri, Jan 11, 2019 at 07:45:05PM +, Head Scratcher via 
Digitalmars-d-learn wrote:
> I am using readText to read a file into a string. I am getting a
> UTFException on the file. It is probably because the file has an
> extended ANSI character that is not UTF-8.
> How can I read the file and convert the string into proper UTF-8 in
> memory without an exception?

What's the encoding of the file?  Without knowing the original encoding,
there is no way to get UTF-8 out of it without the risk of some data
being lost / garbled.

Take a look at std.encoding to see if your file's encoding is already
supported. If not, you may have to read the file in binary and do the
conversion into UTF-8 yourself. Or use an external program to re-encode
your file into UTF-8.  On Posix systems, the 'recode' utility will help
you do this.


T

-- 
To err is human; to forgive is not our policy. -- Samuel Adler


Re: UTFException when reading a file

2019-01-11 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 11 January 2019 at 19:45:05 UTC, Head Scratcher wrote:
How can I read the file and convert the string into proper 
UTF-8 in memory without an exception?


Use regular read() instead of readText, and then convert it use 
another function.


Phobos has std.encoding which offers a transcode function:

http://dpldocs.info/experimental-docs/std.encoding.transcode.html

you would cast to the input type:

---
import std.encoding;
import std.file;

void main() {
string s;
// the read here replaces your readText
// and the cast tells what encoding it has now
transcode(cast(Latin1String) read("o.d"), s);
import std.stdio;
// and after that, the utf-8 string is in s
writeln(s);
}
---


Or, since I didn't like the Phobos module for my web scrape 
needs, I made my own:


https://github.com/adamdruppe/arsd/blob/master/characterencodings.d

Just drop that file in your build and call this function:

http://dpldocs.info/experimental-docs/arsd.characterencodings.convertToUtf8Lossy.html

---
import arsd.characterencodings;
import std.file;

void main() {
 string s = convertToUtf8Lossy(read("o.d"), "iso_8859-1");
 // you can now use s
}
---

just changing the encoding string to whatever it happens to be 
right now.




But it is possible neither my module nor the Phobos one has the 
encoding you need...


UTFException when reading a file

2019-01-11 Thread Head Scratcher via Digitalmars-d-learn
I am using readText to read a file into a string. I am getting a 
UTFException on the file. It is probably because the file has an 
extended ANSI character that is not UTF-8.


How can I read the file and convert the string into proper UTF-8 
in memory without an exception?




Re: Reversing a string

2019-01-11 Thread AlCaponeJr via Digitalmars-d-learn

On Friday, 11 January 2019 at 11:15:05 UTC, Mike James wrote:

Check out the origin :-)

https://forum.dlang.org/thread/hl8345$2b1q$1...@digitalmars.com?page=1


Indeed a terrible name, please don't tell me this was chosen by 
vote.


By the way currently is there any vote system for naming these 
things?


Al.


Re: Reversing a string

2019-01-11 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/11/19 1:25 PM, 0xEAB wrote:

On Friday, 11 January 2019 at 13:51:04 UTC, JN wrote:

On Friday, 11 January 2019 at 11:15:05 UTC, Mike James wrote:

Check out the origin :-)

https://forum.dlang.org/thread/hl8345$2b1q$1...@digitalmars.com?page=1



I guess something like iterReverse, reverseIter, backIterator would be 
too simple...


Of course. I would protrude from all other functions with their weird 
names then.


Just kidding. Although...
I have to admit it happened more than just once that I thought, "oh... 
another function that's named exactly different from what I'd have gone 
with."


Part of the problem is that arr.reverse already was defined a long time ago.

The thing about retro, is that even though it's not what I would think 
of for this operation, I have never forgotten the name since ;)


-Steve


Has anyone tried making a QtCreator plugin for D and what is your experience?

2019-01-11 Thread Enjoys Math via Digitalmars-d-learn
I'm 5 years an expert at PyQt5 in conjunction with 
QtCreator-designed widgets.  Where D is lacking is a good GUI 
editor and GUI library support.


I am starting by building a python-based project called QDmt = 
Qt/D manager


It will do for you, in a cross-platform way, the laborious task 
of compiling the Qt framework from git:


https://wiki.qt.io/Building_Qt_5_from_Git

And also it will guide you through building Qt Creator itself.  
We can then use this tool to help us hack the Qt Creator code and 
make it work for D (assuming a plugin isn't enough).


Building Qt is quite essential, as I am unable to get OpenGL 
support without building it for example.


So not only will we get traffic from TDPL people but from others 
who are only familiar with Qt and had to build it for some 
reason.  This would then be the goto tool for that.


Then they will see firsthand how easy it is (at the click of a 
few buttons) to work with D.


This will cause a huge influx of users to dlang.org and a rift in 
the spacetime continuum!


Re: Coedit almost works for me, except when I go to add peggged

2019-01-11 Thread Enjoys Math via Digitalmars-d-learn

On Friday, 11 January 2019 at 18:36:18 UTC, 0xEAB wrote:

On Friday, 11 January 2019 at 18:27:37 UTC, Enjoys Math wrote:

Dude, that doesn't work either. lol



If you're using DUB, add the dependency manually to your 
project:



"dependencies": {"pegged": "~>0.4.4"}


You will have to be more specific.  I don't see dub.json anywhere 
within Coedit IDE.





Re: Coedit almost works for me, except when I go to add peggged

2019-01-11 Thread 0xEAB via Digitalmars-d-learn

On Friday, 11 January 2019 at 18:27:37 UTC, Enjoys Math wrote:

Dude, that doesn't work either. lol



If you're using DUB, add the dependency manually to your project:


"dependencies": {"pegged": "~>0.4.4"}


Re: All these errors running basic Pegged helloworld example.

2019-01-11 Thread 0xEAB via Digitalmars-d-learn

On Friday, 11 January 2019 at 17:35:40 UTC, Enjoys Math wrote:
Thanks, I downloaded Coedit, but it's not working with pegged 
(using the library manager dub button)


According to your post in [0], it didn't work because you had a 
typo in `pegged`.

Maybe correct it and try again :)

 - Elias


[0] 
https://forum.dlang.org/thread/yhftsrkylskbigoan...@forum.dlang.org


Re: Coedit almost works for me, except when I go to add peggged

2019-01-11 Thread Enjoys Math via Digitalmars-d-learn

On Friday, 11 January 2019 at 17:38:31 UTC, Neia Neutuladh wrote:

On Fri, 11 Jan 2019 17:25:29 +, Enjoys Math wrote:
Package peggged not found for registry at 
https://code.dlang.org/


The package name is pegged, not peggged. Two g's, not three.


Dude, that doesn't work either. lol


Re: Reversing a string

2019-01-11 Thread 0xEAB via Digitalmars-d-learn

On Friday, 11 January 2019 at 13:51:04 UTC, JN wrote:

On Friday, 11 January 2019 at 11:15:05 UTC, Mike James wrote:

Check out the origin :-)

https://forum.dlang.org/thread/hl8345$2b1q$1...@digitalmars.com?page=1



I guess something like iterReverse, reverseIter, backIterator 
would be too simple...


Of course. I would protrude from all other functions with their 
weird names then.


Just kidding. Although...
I have to admit it happened more than just once that I thought, 
"oh... another function that's named exactly different from what 
I'd have gone with."


Re: All these errors running basic Pegged helloworld example.

2019-01-11 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/11/19 1:21 PM, Enjoys Math wrote:

On Friday, 11 January 2019 at 17:44:33 UTC, Michelle Long wrote:

On Sunday, 27 September 2015 at 06:30:37 UTC, Enjoys Math wrote:

[...]


You need to add most of the pegged files... there are more than 3. Try 
adding them all first then remove the junk like the examples, docs, 
etc until it works.


Why should I do that?  There's a DUB feature in Coedit... it should work!


Just keep in mind folks, that the post replied to was from September 2015.

-Steve


Re: All these errors running basic Pegged helloworld example.

2019-01-11 Thread Enjoys Math via Digitalmars-d-learn

On Friday, 11 January 2019 at 17:44:33 UTC, Michelle Long wrote:

On Sunday, 27 September 2015 at 06:30:37 UTC, Enjoys Math wrote:

[...]


You need to add most of the pegged files... there are more than 
3. Try adding them all first then remove the junk like the 
examples, docs, etc until it works.


Why should I do that?  There's a DUB feature in Coedit... it 
should work!


Re: All these errors running basic Pegged helloworld example.

2019-01-11 Thread Michelle Long via Digitalmars-d-learn

On Sunday, 27 September 2015 at 06:30:37 UTC, Enjoys Math wrote:

The example is:

import pegged.grammar;

mixin(grammar(`
Arithmetic:
Term < Factor (Add / Sub)*
Add  < "+" Factor
Sub  < "-" Factor
Factor   < Primary (Mul / Div)*
Mul  < "*" Primary
Div  < "/" Primary
Primary  < Parens / Neg / Pos / Number / Variable
Parens   < "(" Term ")"
Neg  < "-" Primary
Pos  < "+" Primary
Number   < ~([0-9]+)

Variable <- identifier
`));

I'm using Visual D and have C:\MyProjects\D\Pegged (the git 
clone of pegged) added to the add'l imports field under project 
properties > compiler.


I'm getting errors like these:

Error	1	Error 42: Symbol Undefined 
_D6pegged7dynamic7grammar7grammarFAyaHAyaDFS6pegged3peg9ParseTreeZS6pegged3peg9ParseTreeZS6pegged7dynamic7grammar14DynamicGrammar (pegged.dynamic.grammar.DynamicGrammar pegged.dynamic.grammar.grammar(immutable(char)[], pegged.peg.ParseTree delegate(pegged.peg.ParseTree)[immutable(char)[]]))	C:\MyProjects\D\PeggedPractice\	
Error	2	Error 42: Symbol Undefined 
_D6pegged7dynamic7grammar12__ModuleInfoZ	C:\MyProjects\D\PeggedPractice\	


The # of errors was greatly reduced when I added the 3 pegged 
source files to my project.   What can be going wrong?  Thanks!


You need to add most of the pegged files... there are more than 
3. Try adding them all first then remove the junk like the 
examples, docs, etc until it works.


Re: All these errors running basic Pegged helloworld example.

2019-01-11 Thread Enjoys Math via Digitalmars-d-learn

On Sunday, 27 September 2015 at 07:16:51 UTC, BBasile wrote:

On Sunday, 27 September 2015 at 06:30:37 UTC, Enjoys Math wrote:

The example is:

import pegged.grammar;

mixin(grammar(`
Arithmetic:
Term < Factor (Add / Sub)*
Add  < "+" Factor
Sub  < "-" Factor
Factor   < Primary (Mul / Div)*
Mul  < "*" Primary
Div  < "/" Primary
Primary  < Parens / Neg / Pos / Number / Variable
Parens   < "(" Term ")"
Neg  < "-" Primary
Pos  < "+" Primary
Number   < ~([0-9]+)

Variable <- identifier
`));

I'm using Visual D and have C:\MyProjects\D\Pegged (the git 
clone of pegged) added to the add'l imports field under 
project properties > compiler.


I'm getting errors like these:

Error	1	Error 42: Symbol Undefined 
_D6pegged7dynamic7grammar7grammarFAyaHAyaDFS6pegged3peg9ParseTreeZS6pegged3peg9ParseTreeZS6pegged7dynamic7grammar14DynamicGrammar (pegged.dynamic.grammar.DynamicGrammar pegged.dynamic.grammar.grammar(immutable(char)[], pegged.peg.ParseTree delegate(pegged.peg.ParseTree)[immutable(char)[]]))	C:\MyProjects\D\PeggedPractice\	
Error	2	Error 42: Symbol Undefined 
_D6pegged7dynamic7grammar12__ModuleInfoZ	C:\MyProjects\D\PeggedPractice\	


The # of errors was greatly reduced when I added the 3 pegged 
source files to my project.   What can be going wrong?  Thanks!


You must also pass the source root with -I:

-IC:\MyProjects\D\Pegged

(and maybe you miss another source since there are 5:

'..\repos\Pegged\pegged\grammar.d'
'..\repos\Pegged\pegged\parser.d'
'..\repos\Pegged\pegged\peg.d'
'..\repos\Pegged\pegged\dynamic\grammar.d'
'..\repos\Pegged\pegged\dynamic\peg.d'
)

By the way with Coedit you wouldn't have this kind of problems 
(Pegged is part of metaD). You can even run some test on Pegged 
without saving the file / without a project (this is called a 
runnable module). This is just what I've done.


At least compile pegged as a static lib, then it's simpler, you 
just have to pass the -I pegged.lib and your custom 
sources files.


Thanks, I downloaded Coedit, but it's not working with pegged 
(using the library manager dub button)


Re: Coedit almost works for me, except when I go to add peggged

2019-01-11 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 11 Jan 2019 17:25:29 +, Enjoys Math wrote:
> Package peggged not found for registry at https://code.dlang.org/

The package name is pegged, not peggged. Two g's, not three.


Coedit almost works for me, except when I go to add peggged

2019-01-11 Thread Enjoys Math via Digitalmars-d-learn

I open up the Library Manager in Coedit.

I click on the DUB icon.

I enter in 'pegged' then click the green check.

Errors:

Package peggged not found for registry at https://code.dlang.org/ 
(fallback ["registry at http://code.dlang.org/;, "registry at 
https://code-mirror.dlang.io/;, "registry at 
https://code-mirror2.dlang.io/;, "registry at 
https://dub-registry.herokuapp.com/;]): (1): Error: Got JSON of 
type null_, expected object.

(1): Error: Got JSON of type null_, expected object.
error, failed to fetch the package
Fetching pegged ~master...
error, the DUB description cannot be located or it has not the 
JSON format



Fucking fuck, nothing ever works for me... -__-


dub generate visuald shits on me

2019-01-11 Thread Enjoys Math via Digitalmars-d-learn

I do:

dub init simple_type_theory
cd simple_type_theory
dub generate visuald

Errors:

C:\Users\FruitfulApproach\Desktop\_SIMPLE_TYPE_THEORY\simple_type_theory>dub 
generate visuald simple_type_theory
Building package simple_type_theory in 
C:\Users\FruitfulApproach\Desktop\_SIMPLE_TYPE_THEORY\simple_type_theory\
Cannot open file `.dub\simple_type_theory.visualdproj' in mode 
`wb' (No such file or directory)





Re: Print a copyright symbol

2019-01-11 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 11 January 2019 at 16:48:40 UTC, Head Scratcher wrote:
How would I use writeln to print a copyright symbol to the 
console? I have tried using the unicode code \u00A9, as well as 
embedding the symbol directly in the string, but I just get 
garbage when I run it.


You need to be using a system that supports the output.

On Windows, it means changing the console mode to utf-8 so it 
understands the bytes when it sees them.


import core.sys.windows.windows;
SetConsoleOutputCP(65001); // UTF-8

before you do some writeln and it should work on windows 10. On 
older systems, you might have to go into console properties and 
select a truetype font too.


(or as the user btw you can go into console properties and change 
the code page there, but I think it is slightly easier to do it 
on code)


Print a copyright symbol

2019-01-11 Thread Head Scratcher via Digitalmars-d-learn
How would I use writeln to print a copyright symbol to the 
console? I have tried using the unicode code \u00A9, as well as 
embedding the symbol directly in the string, but I just get 
garbage when I run it.




Re: Filter and sort associative array

2019-01-11 Thread Head Scratcher via Digitalmars-d-learn

On Friday, 11 January 2019 at 16:06:48 UTC, Alex wrote:
On Friday, 11 January 2019 at 16:02:27 UTC, Head Scratcher 
wrote:
Thank you. This works great. What I don't understand is how a 
key-value pair ends up being a set of strings. Where did the 
value of the key-value pair get removed?  According to the 
library documentation, the array function "allocates an array 
and initializes it with copies of the elements of range r." So 
wouldn't the resulting array contain pairs? And if so, how 
does the sort work on pairs?


By map you map the pair to its key resp. its first element. The 
result of the map contains the right-hand side of the "=>" 
expression only.


Ah, that makes sense. Thank you for the explanation.


Re: Creating fixed array on stack

2019-01-11 Thread Johan Engelen via Digitalmars-d-learn

On Friday, 11 January 2019 at 15:23:08 UTC, Dgame wrote:

On Friday, 11 January 2019 at 14:46:36 UTC, Andrey wrote:

Hi,
In C++ you can create a fixed array on stack:

int count = getCount();
int myarray[count];


Small correction: this is valid in C, but not in C++.

In D the "count" is part of type and must be known at CT but 
in example it is RT.

How to do such thing in D? Without using of heap.


You could try alloca:


Indeed, but make sure you read up on the caveats of using alloca. 
I believe all use cases of VLA/alloca have better alternative 
implementation options.


-Johan



Re: Filter and sort associative array

2019-01-11 Thread Alex via Digitalmars-d-learn

On Friday, 11 January 2019 at 16:02:27 UTC, Head Scratcher wrote:
Thank you. This works great. What I don't understand is how a 
key-value pair ends up being a set of strings. Where did the 
value of the key-value pair get removed?  According to the 
library documentation, the array function "allocates an array 
and initializes it with copies of the elements of range r." So 
wouldn't the resulting array contain pairs? And if so, how does 
the sort work on pairs?


By map you map the pair to its key resp. its first element. The 
result of the map contains the right-hand side of the "=>" 
expression only.


Re: Filter and sort associative array

2019-01-11 Thread Head Scratcher via Digitalmars-d-learn
Thank you. This works great. What I don't understand is how a 
key-value pair ends up being a set of strings. Where did the 
value of the key-value pair get removed?  According to the 
library documentation, the array function "allocates an array and 
initializes it with copies of the elements of range r." So 
wouldn't the resulting array contain pairs? And if so, how does 
the sort work on pairs?


Re: Filter and sort associative array

2019-01-11 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/11/19 10:20 AM, Head Scratcher wrote:

I am just learning D. So far, I am impressed by its elegance and power.

I have an associative array bool[string]. I want to filter it by value 
(!bool), then extract the keys and sort them. I am struggling with the 
syntax and working with ranges. I can't find any documentation related 
to filtering associative arrays.


This is what I currently have, but it doesn't compile:

auto sortedStrings = myAssocArray.byKeyValue.filter!((string k,value) => 
!value).assocArray.keys.sort();





import std.range;
import std.algorithm;
import std.array;

auto sortedStrings = myAssocArray
.byKeyValue
.filter!(kvp => !kvp.value) // kvp = key value pair
.map!(kvp => kvp.key)   // map to the key strings
.array  // form a sortable array
.sort;  // sort it

Note the nice formatting to show how the range pipeline goes, and allows 
for comments explaining each step.


-Steve


Re: Filter and sort associative array

2019-01-11 Thread H. S. Teoh via Digitalmars-d-learn
On Fri, Jan 11, 2019 at 03:20:20PM +, Head Scratcher via 
Digitalmars-d-learn wrote:
> I am just learning D. So far, I am impressed by its elegance and power.
> 
> I have an associative array bool[string]. I want to filter it by value
> (!bool), then extract the keys and sort them. I am struggling with the
> syntax and working with ranges. I can't find any documentation related to
> filtering associative arrays.
> 
> This is what I currently have, but it doesn't compile:
> 
> auto sortedStrings = myAssocArray.byKeyValue.filter!((string k,value) =>
> !value).assocArray.keys.sort();

I recommend using std.array.byPair rather than .byKeyValue, like this:

auto sortedStrings = myAssocArray.byPair
.filter!(pair => !pair[1])  // pair[1] is the value
.map!(pair => pair[0])  // pair[0] is the key
.array
.sort;

The .array call is needed because .byPair returns a non-random access
range, which cannot be sorted. So you need to create an array first then
sort that.

Also, there's no need to reconstruct another AA with the filtered
entries -- it allocates a new AA which is wasteful.  All you really need
is the filter the keys, then sort the keys.


T

-- 
If the comments and the code disagree, it's likely that *both* are wrong. -- 
Christopher


Re: Creating fixed array on stack

2019-01-11 Thread Dgame via Digitalmars-d-learn

On Friday, 11 January 2019 at 14:46:36 UTC, Andrey wrote:

Hi,
In C++ you can create a fixed array on stack:

int count = getCount();
int myarray[count];


In D the "count" is part of type and must be known at CT but in 
example it is RT.

How to do such thing in D? Without using of heap.


You could try alloca:


import core.stdc.stdlib: alloca;

pragma(inline, true) auto stack(T, alias len)(void* p = 
alloca(T.sizeof * len)) {

return (cast(T*) p)[0 .. len] = T.init;
}

void main() {
import std.stdio: writeln;

int size = 42;
auto a = stack!(int, size);
writeln(a);
a[] = 2;
writeln(a);
}



Filter and sort associative array

2019-01-11 Thread Head Scratcher via Digitalmars-d-learn
I am just learning D. So far, I am impressed by its elegance and 
power.


I have an associative array bool[string]. I want to filter it by 
value (!bool), then extract the keys and sort them. I am 
struggling with the syntax and working with ranges. I can't find 
any documentation related to filtering associative arrays.


This is what I currently have, but it doesn't compile:

auto sortedStrings = myAssocArray.byKeyValue.filter!((string 
k,value) => !value).assocArray.keys.sort();





Creating fixed array on stack

2019-01-11 Thread Andrey via Digitalmars-d-learn

Hi,
In C++ you can create a fixed array on stack:

int count = getCount();
int myarray[count];


In D the "count" is part of type and must be known at CT but in 
example it is RT.

How to do such thing in D? Without using of heap.


Re: Generating API documention

2019-01-11 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 10 January 2019 at 07:04:52 UTC, George wrote:
What do people use to generate nice looking and simple html 
documentation for their projects?


If you like my style 
 
and syntax 
 you can use my site.


If you wanna run yourself, go here: 
https://github.com/adamdruppe/adrdox clone that, hit make (on 
Linux at least) and run the program: `./doc2 
/path/to/your/project`. It spits out html in a generated-docs 
folder.



OR if you are on the code.dlang.org dub repository, I have a 
server that will run it all for you by just going to


your-dub-project-name.dpldocs.info


Re: Reversing a string

2019-01-11 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 11 January 2019 at 13:51:04 UTC, JN wrote:
I guess something like iterReverse, reverseIter, backIterator 
would be too simple...


or foreach_reverse, which never actually was removed!

lol


Re: Reversing a string

2019-01-11 Thread JN via Digitalmars-d-learn

On Friday, 11 January 2019 at 11:15:05 UTC, Mike James wrote:

Check out the origin :-)

https://forum.dlang.org/thread/hl8345$2b1q$1...@digitalmars.com?page=1



I guess something like iterReverse, reverseIter, backIterator 
would be too simple...




Re: Reversing a string

2019-01-11 Thread AndreasDavour via Digitalmars-d-learn

On Friday, 11 January 2019 at 11:15:05 UTC, Mike James wrote:

On Friday, 11 January 2019 at 09:41:30 UTC, bauss wrote:

On Friday, 11 January 2019 at 08:25:41 UTC, Seb wrote:
On Friday, 11 January 2019 at 08:05:39 UTC, AndreasDavour 
wrote:

Hi.

I've just started to learn some D, so maybe this question is 
extremely stupid, but please bear with me.


[...]


Use .retro - it is also lazy and won't allocate:

https://run.dlang.io/is/A6bjrC


What a terrible name.


Check out the origin :-)

https://forum.dlang.org/thread/hl8345$2b1q$1...@digitalmars.com?page=1


-=mike=-



Look at that.

Incidentally, I kind of like "foreach(i; 99 .. 0 : -1)".


Re: Reversing a string

2019-01-11 Thread bauss via Digitalmars-d-learn

On Friday, 11 January 2019 at 11:15:05 UTC, Mike James wrote:

On Friday, 11 January 2019 at 09:41:30 UTC, bauss wrote:

On Friday, 11 January 2019 at 08:25:41 UTC, Seb wrote:
On Friday, 11 January 2019 at 08:05:39 UTC, AndreasDavour 
wrote:

Hi.

I've just started to learn some D, so maybe this question is 
extremely stupid, but please bear with me.


[...]


Use .retro - it is also lazy and won't allocate:

https://run.dlang.io/is/A6bjrC


What a terrible name.


Check out the origin :-)

https://forum.dlang.org/thread/hl8345$2b1q$1...@digitalmars.com?page=1


-=mike=-


I wish I could live my life peacefully, but apparently not.



Re: SerialPort

2019-01-11 Thread UlanReed via Digitalmars-d-learn
For me 
https://www.virtual-serial-port.org/products/serialmonitor/ is an 
ideal way to track down problems that may occur during 
application or driver development, testing and optimization of 
serial devices and i use this soft all time.


Re: Reversing a string

2019-01-11 Thread Mike James via Digitalmars-d-learn

On Friday, 11 January 2019 at 09:41:30 UTC, bauss wrote:

On Friday, 11 January 2019 at 08:25:41 UTC, Seb wrote:
On Friday, 11 January 2019 at 08:05:39 UTC, AndreasDavour 
wrote:

Hi.

I've just started to learn some D, so maybe this question is 
extremely stupid, but please bear with me.


[...]


Use .retro - it is also lazy and won't allocate:

https://run.dlang.io/is/A6bjrC


What a terrible name.


Check out the origin :-)

https://forum.dlang.org/thread/hl8345$2b1q$1...@digitalmars.com?page=1


-=mike=-


Re: Reversing a string

2019-01-11 Thread AndreasDavour via Digitalmars-d-learn

On Friday, 11 January 2019 at 09:41:30 UTC, bauss wrote:

On Friday, 11 January 2019 at 08:25:41 UTC, Seb wrote:
On Friday, 11 January 2019 at 08:05:39 UTC, AndreasDavour 
wrote:

Hi.

I've just started to learn some D, so maybe this question is 
extremely stupid, but please bear with me.


[...]


Use .retro - it is also lazy and won't allocate:

https://run.dlang.io/is/A6bjrC


What a terrible name.


Well, it was not the first one I would have searched for, no.

Good to know it exists as well, though. Thanks!


Re: Reversing a string

2019-01-11 Thread bauss via Digitalmars-d-learn

On Friday, 11 January 2019 at 08:25:41 UTC, Seb wrote:

On Friday, 11 January 2019 at 08:05:39 UTC, AndreasDavour wrote:

Hi.

I've just started to learn some D, so maybe this question is 
extremely stupid, but please bear with me.


[...]


Use .retro - it is also lazy and won't allocate:

https://run.dlang.io/is/A6bjrC


What a terrible name.


Re: Segfault when adding a static destructor in druntime/src/rt/sections_elf_shared.d

2019-01-11 Thread RazvanN via Digitalmars-d-learn
On Thursday, 10 January 2019 at 23:04:37 UTC, Steven 
Schveighoffer wrote:

On 1/10/19 5:12 PM, RazvanN wrote:
On Thursday, 10 January 2019 at 15:04:25 UTC, Steven 
Schveighoffer wrote:

On 1/8/19 7:54 AM, RazvanN wrote:

[...]


That is a thread-local static destructor. Are any shared 
static destructors accessing the array?


No, there aren't. Indeed, the problem is as Johan as said: the 
loadedDSOs should not be wrapped in an array with a destructor 
because it is manually destroyed.


Hm... is this a sign of how things will be once the (necessary 
IMO) change to destroying globals is deployed?


-Steve


At least for this specific situation, yes.


Packing 5-bit words into size_t-aligned bit-array

2019-01-11 Thread Per Nordlöw via Digitalmars-d-learn
I want to pack a letters from a char[] into an array of 5-bit 
encoded English lower letters in a size_t[2].


How do I accomplish that with as few instructions as possible?

I currently have

size_t[2] words;
enum charBits = 5;
foreach (const ch_index, const char ch; expr)
{
ubyte ub = 0;
if (ch >= 'a' && ch <= 'z') // English lower letter
{
ub = cast(ubyte)(ch - 'a');
}
else if (ch == ' ') // space
{
ub = cast(ubyte)(ch - 'z' + 1);
}
else
{
dln("Invalid char ", ch);
assert(0);
}
assert(ub < (1 << charBits), "Too large ubyte code");
const bit_index = 8 + charBits*ch_index; // first 8 
bits reserved for length
// TODO store first `charBits` bits of `ub` at 
`bit_index` in `words`

}



Re: Reversing a string

2019-01-11 Thread AndreasDavour via Digitalmars-d-learn

On Friday, 11 January 2019 at 08:45:12 UTC, JN wrote:
On Friday, 11 January 2019 at 08:15:01 UTC, rikki cattermole 
wrote:
Note the immutable, it means you cannot modify individual 
values. Which is a problem for reverse because it modifies in 
place.




The error message is kind of unfortunate. This is a simple 
usecase and the error message is undecipherable already. It'd 
be cool if the compiler could try to strip immutability, and if 
the type matches then, throw an error something like "Cannot 
pass immutable char[] to reverse, did you mean char[]?".


That would help a lot, as I got "rikki cattermole"'s answer at 
once, when my eyes were brought to the "immutable" part.


I come from the lisp world, so I'm kind of familiar with the idea 
of copying and/or modifying in place to limit consing. I guess I 
should I have realised this would be a perfect example of that 
kind of situation.


Re: Reversing a string

2019-01-11 Thread JN via Digitalmars-d-learn
On Friday, 11 January 2019 at 08:15:01 UTC, rikki cattermole 
wrote:
Note the immutable, it means you cannot modify individual 
values. Which is a problem for reverse because it modifies in 
place.




The error message is kind of unfortunate. This is a simple 
usecase and the error message is undecipherable already. It'd be 
cool if the compiler could try to strip immutability, and if the 
type matches then, throw an error something like "Cannot pass 
immutable char[] to reverse, did you mean char[]?".


Re: Reversing a string

2019-01-11 Thread Seb via Digitalmars-d-learn

On Friday, 11 January 2019 at 08:05:39 UTC, AndreasDavour wrote:

Hi.

I've just started to learn some D, so maybe this question is 
extremely stupid, but please bear with me.


[...]


Use .retro - it is also lazy and won't allocate:

https://run.dlang.io/is/A6bjrC


Re: Reversing a string

2019-01-11 Thread rikki cattermole via Digitalmars-d-learn
So strings in D are Unicode. This is both a great thing and a horrible 
thing.
To reverse a Unicode string correctly you need to take into account BiDi 
and graphemes, in other words it gets rather complex. However I suspect 
that this isn't what you want.


Now a (w/d)string is defined as:

alias string  = immutable(char)[];
alias wstring = immutable(wchar)[];
alias dstring = immutable(dchar)[];

Note the immutable, it means you cannot modify individual values. Which 
is a problem for reverse because it modifies in place.


Which means:

writeln("Hello D".reverse);

Won't work, but:

writeln("Hello D".dup.reverse);

Will. A simple duplication (char[]) makes it work.

Finally, arrays in D are absolutely brilliant. They are what we call 
slices. A slice is a pointer + a length. That is it. Hence they cannot 
be reversed in place. Of course this is great for interacting with e.g. 
C, since its just a matter of slicing any data back to get your bounds 
checking ext.


Reversing a string

2019-01-11 Thread AndreasDavour via Digitalmars-d-learn

Hi.

I've just started to learn some D, so maybe this question is 
extremely stupid, but please bear with me.


I have been trying to reverse a string, and through some googling 
found the std.algorithm.mutation.reverse method. But, when I try 
to use it I get some very verbose errors that just makes my eyes 
glaze over. What on earth do they mean? How do I reverse a 
string, really?


This is my code:

import std.stdio;
import std.algorithm;

void main() {
  auto test = "This is my text";
  string next_test = reverse(test);

  writeln(test);
  writeln(next_test);
}


This is my error:

[ante@tiny ~/src/D/tutorial]$ rdmd string4.d
/usr/home/ante/src/dmd2/freebsd/bin64/../../src/phobos/std/algorithm/mutation.d(2513):
 Error: template `std.algorithm.mutation.reverse` cannot deduce function from 
argument types `!()(immutable(ubyte)[])`, candidates are:
/usr/home/ante/src/dmd2/freebsd/bin64/../../src/phobos/std/algorithm/mutation.d(2485):
`std.algorithm.mutation.reverse(Range)(Range r) if (isBidirectionalRange!Range && 
(hasSwappableElements!Range || hasAssignableElements!Range && hasLength!Range && 
isRandomAccessRange!Range || isNarrowString!Range && isAssignable!(ElementType!Range)))`
/usr/home/ante/src/dmd2/freebsd/bin64/../../src/phobos/std/algorithm/mutation.d(2521):
 Error: template `std.algorithm.mutation.reverse` cannot deduce function from 
argument types `!()(immutable(ubyte)[])`, candidates are:
/usr/home/ante/src/dmd2/freebsd/bin64/../../src/phobos/std/algorithm/mutation.d(2485):
`std.algorithm.mutation.reverse(Range)(Range r) if (isBidirectionalRange!Range && 
(hasSwappableElements!Range || hasAssignableElements!Range && hasLength!Range && 
isRandomAccessRange!Range || isNarrowString!Range && isAssignable!(ElementType!Range)))`
string4.d(6): Error: template instance 
`std.algorithm.mutation.reverse!string` error instantiating
Failed: ["/usr/home/ante/src/dmd2/freebsd/bin64/dmd", "-v", 
"-o-", "string4.d", "-I."]

--

Can some unpack that for me, please?

I might add that the most intuitive way to reverse a string, I 
think, would be to consider it a range and just do "newstring = 
oldstring[$ .. 0]" but that gives an error about being out of 
bounds, so I guess the compiler expect values to increase from 
left to right, and does not want to increment beyond $. Makes 
sense, but that syntax would be very neat.