Re: range.save

2015-11-24 Thread Freddy via Digitalmars-d
On Tuesday, 24 November 2015 at 01:53:39 UTC, Steven 
Schveighoffer wrote:

...
I can't quite think of an example right now but there was a 
thread about this a few years ago. 
http://forum.dlang.org/thread/twnymbxfdmqupsfjf...@forum.dlang.org


Re: range.save

2015-11-23 Thread Freddy via Digitalmars-d

On Thursday, 19 November 2015 at 21:30:23 UTC, Freddy wrote:

...
Another problem I noticed with ranges is that all functionality 
is unionized. Ranges are expected to be able to 
popFront,Index,popBack, randomly possibly forcing ranges to carry 
unneeded buffers if indexing or popBack in never used.


On possible solution is to have .retroRange and .indexRange On 
forward/input ranges.


Re: range.save

2015-11-23 Thread Freddy via Digitalmars-d
On Tuesday, 24 November 2015 at 01:03:36 UTC, Steven 
Schveighoffer wrote:
surely you mean opIndex? Note that ranges are required to 
implement front, popFront, and empty. That's it, then it is a 
range. Even save isn't required unless you want it to be a 
forward range.


I meant .indexableRange, random access may require extra buffers 
or stack space that take space even when random access isn't 
used, and I'm asking for optional members(.retroRange, 
.indexableRange)


But yes, a fundamental requirement is to be able to get the 
front element repeatedly. This necessitates a buffer or "saving 
of state".


Not quite what I was thinking. I was saying that ranges that 
implement back,popBack may need to implement a backwards buffer 
along a forward buffer even if the backwards buffer is never used.


range.save

2015-11-19 Thread Freddy via Digitalmars-d
Does anyone else think range.save is a hack? I often find myself 
forgetting to call range.save in my generic code with my 
unittests working fine. Also, working with a range of ranges may 
forget to call range.save.(Ex: [1,2,4].repeat)


std.range.only with different range types

2015-11-08 Thread Freddy via Digitalmars-d-learn

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

void main(){
only(iota(0,4),[1,4,5]).writeln;
}
---
How can I call std.range.only with different range types?


generate with state

2015-11-02 Thread Freddy via Digitalmars-d-learn
Is there a version of 
http://dlang.org/phobos/std_range.html#.generate with state.


Re: generate with state

2015-11-02 Thread Freddy via Digitalmars-d-learn

On Tuesday, 3 November 2015 at 00:08:54 UTC, Ali Çehreli wrote:

generate() already allows "callables", which can be a delegate:

import std.stdio;
import std.range;

struct S {
int i;

int fun() {
return i++;
}
}

void main() {
auto s = S(42);
writefln("%(%s %)", generate().take(5));
}

Prints

42 43 44 45 46


Will that allocate gc memory? Is there any why I pass state as a 
tuple and have my generator modify state as It's called?




Unionize range types

2015-11-02 Thread Freddy via Digitalmars-d-learn

Is there any way I can Unionize range Types?
---
auto primeFactors(T)(T t, T div = 2)
{
if (t % div == 0)
{
return t.only.chain(primeFactors(t / div, div));
}
if (div > t)
{
return [];
}
else
{
return primeFactors(t, div + 1);
}
}

---


Re: good reasons not to use D?

2015-11-01 Thread Freddy via Digitalmars-d-learn

On Friday, 30 October 2015 at 10:35:03 UTC, Laeeth Isharc wrote:

I'm writing a talk for codemesh on the use of D in finance.

I want to start by addressing the good reasons not to use D.  
(We all know what the bad ones are).  I don't want to get into 
a discussion here on them, but just wanted to make sure I cover 
them so I represent the state of affairs correctly.


So far what comes to mind: heavy GUI stuff (so far user 
interface code is not what it could be); cases where you want 
to write quick one-off scripts that need to use a bunch of 
different libraries not yet available in D and where it doesn't 
make sense to wrap or port them; where you have a lot of code 
in another language (especially non C, non Python) and defining 
an interface is not so easy; where you have many inexperienced 
programmers and they need to be productive very quickly.


Any other thoughts?


I would advise against using D in applications where memory is 
essential. Idiomatic D uses a garbage collector which has a non 
free runtime cost.


Re: std.algorithm.startsWith only predicate

2015-10-18 Thread Freddy via Digitalmars-d-learn

On Sunday, 18 October 2015 at 17:58:30 UTC, Meta wrote:
Is this a simplified use case of some actual code you have? 
Otherwise, you can just do:



bool iden(string str)
{
auto f = str.front;
return f.isAlpha || f == '_';
}


It's simplified, i wanted to check for empty


std.algorithm.startsWith only predicate

2015-10-18 Thread Freddy via Digitalmars-d-learn

How do you call startsWith with only a predicate
---
import std.algorithm;
import std.ascii;

bool iden(string str)
{
return str.startsWith!(a => a.isAlpha || a == '_');
}
---


Alias lamda argument vs Type template argument

2015-10-15 Thread Freddy via Digitalmars-d-learn
There are two these different ways to pass functions as template 
arguments. Which is preferred?

---
void funcA(alias calle)()
{
calle();
}

void funcB(T)(T calle)
{
calle();
}

void main()
{
funcA!(() => 0);
funcB(() => 0);
}
---


Re: DIP74 - where is at?

2015-10-11 Thread Freddy via Digitalmars-d

On Sunday, 11 October 2015 at 05:52:45 UTC, Freddy wrote:
Speaking of DIP74 can't we just wrap a class in a struct with 
use reference counting with and use alias this?


Also how will DIP74 work with incremental compilation?
---
extern (D) class RcClass;

void func(RcClass a)
{
//opps
auto b = a;
return;
}
---


Re: DIP74 - where is at?

2015-10-11 Thread Freddy via Digitalmars-d
On Sunday, 11 October 2015 at 06:10:32 UTC, Jonathan M Davis 
wrote:
alias is problematic, because it allows the class reference to 
escape. opDispatch doesn't have that problem, though there may 
be other complications that it introduces (I don't know). It 
does get kind of complicated though when you consider member 
functions which return the a reference to the object and things 
like that. So, while it's generally feasible, it's not that 
hard for it to become unsafe. How much that matters is 
debatable, but it could make it so that reference counting 
classes is infeasible in @safe code.


- Jonathan M Davis


Can't we make opAssign and this(this) work with classes add 
@disable to them? Also rec counted classes shouldn't have members 
of that have their type, they should have to have members of the 
aliased struct containing their type.


Re: DIP74 - where is at?

2015-10-10 Thread Freddy via Digitalmars-d

On Saturday, 10 October 2015 at 23:25:49 UTC, Manu wrote:

[...]


Speaking of DIP74 can't we just wrap a class in a struct with use 
reference counting with and use alias this?


Re: DIP74 - where is at?

2015-10-10 Thread Freddy via Digitalmars-d

On Sunday, 11 October 2015 at 04:16:11 UTC, deadalnix wrote:
The problem at hand is fairly well know at this stage: it is 
ownership. Everything else can be done as library.


This.


Re: -> and :: operators

2015-10-09 Thread Freddy via Digitalmars-d

On Friday, 9 October 2015 at 04:15:42 UTC, Ali Çehreli wrote:
Semi-relatedly, a colleague who has heard many D sales pitches 
from me over the years is recently "looking at Go" and liking 
it very much. He came to me today telling me about this awesome 
Go feature where you just type a dot after a pointer and the 
language is so great that it works! You don't need to type 
(*p).member. Isn't Go awesome!


I responded "yep, it's a great feature and those gostards will 
never admit that they took that feature from D." (There is 
probably earlier precedence but it felt great to say it to my 
friend. :) )


Ali


Stole from D? You mean java right?


Re: Moving back to .NET

2015-10-08 Thread Freddy via Digitalmars-d

On Thursday, 8 October 2015 at 14:02:58 UTC, Chris wrote:

It'd be nice to have asm.js or even JS.


The major ploblem I see right now with targeting asm.js is 
garbage collection. This can be worked around (I think) by having 
all pointers be fat pointers (size_t* stack_ref_count,T* data) 
and by having write barriers (that check for null for 
stack_ref_count) when coping pointers.


Re: Moving back to .NET

2015-10-08 Thread Freddy via Digitalmars-d

On Thursday, 8 October 2015 at 10:31:57 UTC, Chris wrote:

2. Solid non-gc memory management and ownership.


Any specific implementation in mind?


Well the first step to that should be implement a way to make 
sure pointers don't escape their scope.


Fibers and Ranges

2015-10-04 Thread Freddy via Digitalmars-d

---
import core.thread;
import std.conv;
import std.stdio;

void formatStuff(P)(P put, int stuff)
{
put("a");
put("b");
put("c");
put(stuff);
foreach (i; 0 .. 10)
{
put(i ^^ stuff);
}
}

auto formatRange(alias sub, T...)(T args)
{
class FormatFiber : Fiber
{
string front_;
this()
{
super();
popFront;
}

void run()
{
sub(this, args);
}

void opCall(T)(T t)
{
front_ = t.to!string;
yield;
}

void popFront()
{
call;
}

@property:
string front()
{
return front_;
}

bool empty()
{
return state != State.HOLD;
}
}

return new FormatFiber;
}

void main()
{
writeln(formatRange!formatStuff(5));
}
---
Another Idea thoughts?


How to use std.range.interfaces in pure @safe code

2015-10-02 Thread Freddy via Digitalmars-d-learn
How do I use http://dlang.org/phobos/std_range_interfaces.html in 
pure @safe code?


Range of variables

2015-09-30 Thread Freddy via Digitalmars-d-learn

Is there a way to make a range of a variables lazily?
---
int var1;
int var2;
void func()
{
int var3;
auto range = /*range of var1,var2,var3*/ ;
}
---


address of overloaded function

2015-09-30 Thread Freddy via Digitalmars-d-learn
How do you take the address of a specific overloaded function. 
This won't compile

---
import std.range;

void main()
{
ForwardAssignable!int range;
int delegate() @property get = 
void delegate(int) @property set = 
}
---


Re: Shout out to D at cppcon, when talkign about ranges.

2015-09-29 Thread Freddy via Digitalmars-d

On Wednesday, 30 September 2015 at 01:45:49 UTC, deadalnix wrote:

https://www.youtube.com/watch?v=mFUXNMfaciE

From
http://wiki.dlang.org/Component_programming_with_ranges

Congrat H. S. Teoh


So this is what APL feels like. /s


Idioms you use

2015-09-28 Thread Freddy via Digitalmars-d

Are any D idioms you use that you like to share?
Heres one of mine
---
enum ctfe =
{
return 0xdead & 0xbad;
}();
---


Bug or feature storage class alias

2015-09-26 Thread Freddy via Digitalmars-d

Is this a bug or a feature
---
import std.stdio;

int global;

alias cGlobal = const global;
alias sGlobal = shared global;

void main()
{
global = 5;
writeln(cGlobal);
global = 7;
writeln(sGlobal);
}
---


Re: Bug or feature storage class alias

2015-09-26 Thread Freddy via Digitalmars-d

On Saturday, 26 September 2015 at 20:27:03 UTC, Freddy wrote:

Is this a bug or a feature

I forgot to show that sGlobal is writable



Re: Bug or feature storage class alias

2015-09-26 Thread Freddy via Digitalmars-d

On Saturday, 26 September 2015 at 20:27:03 UTC, Freddy wrote:

Is this a bug or a feature
Wait nevermind me, the compiler ignores those storage classes if 
the alias is to a symbol.


.h in dmd source code

2015-09-26 Thread Freddy via Digitalmars-d
Under dmd's source 
code(https://github.com/D-Programming-Language/dmd/tree/master/src) there are some .h files, wasn't  dmd supported to converted to D? Why are the .h files still there?


scope in function argument

2015-09-23 Thread Freddy via Digitalmars-d-learn

What does it mean when there is a scope in a function argument.
---
void func(scope int* a){}
---


Re: Stroustrup is disappointed with D :(

2015-09-22 Thread Freddy via Digitalmars-d

On Tuesday, 22 September 2015 at 18:58:31 UTC, Tourist wrote:

"D disappointed me so much when it went the Java way".
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#to-do-unclassified-proto-rules

It's something about virtual calls, but I didn't understand 
what he means. What does he mean?


I doubt he is talking about the whole language. From my skimming 
it seems he is talking about how D copies java's classes.


Re: Implementing typestate

2015-09-15 Thread Freddy via Digitalmars-d

On Tuesday, 15 September 2015 at 21:44:25 UTC, Freddy wrote:

On Tuesday, 15 September 2015 at 17:45:45 UTC, Freddy wrote:

 Rust style memory management in a library


Wait nevermind about that part, it's harder than I thought.


All hope might not be lost, something like this MIGHT work,but 
i'm am sure I am missing some kind of detail.

---
//doesn't actually compile
struct MutBorrow(T, bool usable_ = true)
{
private T** ptr;
enum usable = usable_;
static if (usable)
{
@disable this();
ref T use()
{
return **ptr;
}
}
//...
}

struct Unique(T)
{
private T* ptr;

alias user = null;

~this()
{
static assert(user is null);
free(ptr);
}

auto giveMut(alias local)()
{
static assert(is(user : null)));
user = local;
local.usable = true;
local.ptr = 
}

auto takeMut(alias local)()
{
static assert(local == user); //is there a proper way to 
compare alias?

user = null;
local.usable = false;
}

static if ( /+user not null+/ )
{
ref T use()
{
return *ptr;
}
}
}
---


Re: Implementing typestate

2015-09-15 Thread Freddy via Digitalmars-d

On Tuesday, 15 September 2015 at 17:45:45 UTC, Freddy wrote:

 Rust style memory management in a library


Wait nevermind about that part, it's harder than I thought.


Re: Implementing typestate

2015-09-15 Thread Freddy via Digitalmars-d

On Tuesday, 15 September 2015 at 17:45:45 UTC, Freddy wrote:

...


I just thought of some corner cases and how to solve them.
---
Disallow global variable with typestate (there might be a better 
solution down the line).
The evaluated typestate of variables after going through  
branches (if,for,etc...) must be the same.

Example
---
void func(){
File f;
if(someVar){
f.openWrite("a.txt");
}
//error here one branch where f is none, another branch where 
f is open

}
---


Re: Implementing typestate

2015-09-15 Thread Freddy via Digitalmars-d

On Tuesday, 15 September 2015 at 17:57:10 UTC, BBasile wrote:


This won't work in D. Everything that's static is common to 
each instance.
What's possible however is to use an immutable FState that's 
set in the ctor.


---
struct File
{
immutable FState state,
this(string fname, FState st){state = st}
}
---

Than you're sure that your file state can't be changed by error.
Otherwise just hide the state to set it as a private variable...


No, I'm talking about adding a new feature to the language, 
modifable enums(typestate).


Re: Implementing typestate

2015-09-15 Thread Freddy via Digitalmars-d

On Tuesday, 15 September 2015 at 18:10:06 UTC, BBasile wrote:

Ok, sorry I didn't know this concept so far.
So there would be a kind of 'compile-time instance' of File 
with a modifiable member ?


A simplified version of this: 
https://en.wikipedia.org/wiki/Typestate_analysis
Where types can have compile time state(enum) that change as they 
are used.


Implementing typestate

2015-09-15 Thread Freddy via Digitalmars-d
Would it be worth implementing some kind of typestate into the 
language?

By typestate I mean a modifiable enum.

For example:
---
enum FState
{
none,
read,
write
}

struct File
{
//maybe another keyword other than enum
enum state = FState.none;

void openRead(string name)
{
//evalutaed in a way similar to static if
state = FState.read;
//...
}

void openWrite(string name)
{
state = FState.write;
//...
}

ubyte[] read(size_t) if (state == FState.read)
{
//...
}

void write(ubyte[]) if (state == FState.write)
{
//...
}
}

unittest
{
File f;
static assert(f.state == FState.none);
f.openRead("a.txt");
static assert(f.state == FState.read);
auto data = f.read(10);
}
---

We could use this "typestate" to implement:
 Rust style memory management in a library
 Safer Files (as shown)
 Possibly other ideas

Thoughts?


Rust style memory management

2015-09-12 Thread Freddy via Digitalmars-d
So I saw this video: 
https://air.mozilla.org/guaranteeing-memory-safety-in-rust/ and 
was amazed. Is there any way we can implement this in D? What 
language extensions would be required?


My idea on implement this would be to add 3 new pointer (and 
array) types : [owned,shared immutable,borrow mutable] and depend 
on casting raw pointers to the new types.


Thoughts?


Re: Range functions expand char to dchar

2015-09-09 Thread Freddy via Digitalmars-d

On Tuesday, 8 September 2015 at 18:28:40 UTC, Matt Kline wrote:

A bit verbose, but I suppose that will do.

You could use map
---
import std.algorithm : map;
import std.utf : byCodeUnit;
import std.array : array;

auto arr = ["foo", "bar", "baz"].map!(a => a.byCodeUnit).array;
---


Re: Member function pointers

2015-09-09 Thread Freddy via Digitalmars-d

On Wednesday, 9 September 2015 at 20:18:06 UTC, Freddy wrote:
enum MemberFunc(alias Type, string member) = (ref Type self, 
Parameters!(__traits(getMember, Type, member)) args) => 
mixin(q{self.} ~ member ~ q{(args)});


Whoops the alias wasn't needed

enum MemberFunc(Type, string member) = (ref Type self, 
Parameters!(__traits(getMember, Type, member)) args) => 
mixin(q{self.} ~ member ~ q{(args)});




Re: Member function pointers

2015-09-09 Thread Freddy via Digitalmars-d
On Wednesday, 9 September 2015 at 18:55:18 UTC, Walter Bright 
wrote:

On 6/10/2013 7:33 AM, Manu wrote:

[...]


Sorry to say, your n.g. poster is back to its old tricks :-)


On 6/10/2013
That was 2 years ago.


Re: Member function pointers

2015-09-09 Thread Freddy via Digitalmars-d
On Wednesday, 9 September 2015 at 18:50:45 UTC, Walter Bright 
wrote:

On 6/7/2013 4:21 PM, Manu wrote:
So from my dconf talk, I detailed a nasty hack to handle 
member function

pointers in D.


https://www.digitalmars.com/articles/b68.html


Here's on automatic version

import std.traits : Parameters;

enum MemberFunc(alias Type, string member) = (ref Type self, 
Parameters!(__traits(getMember, Type, member)) args) => 
mixin(q{self.} ~ member ~ q{(args)});


unittest
{
static struct A
{
bool test;
void b(int arg)
{
test = arg == 4;
}
}

A a;
auto func = MemberFunc!(A, "b");
func(a,4);
assert(a.test);
}



Re: Error reporting is terrible

2015-09-04 Thread Freddy via Digitalmars-d

On Friday, 4 September 2015 at 00:10:46 UTC, Xinok wrote:
Again, specific examples would help. Often, when newcomers 
detail the trouble they encountered during their first 
experience with D, one or more people will get to work fixing 
or alleviating the specific issues they mention.


Not the op,but stack traces with line numbers would be nice.


My problem with const

2015-09-04 Thread Freddy via Digitalmars-d
I love the way D does transitive const and immutable but i have a 
problem when i use const a struct field.

---
struct MyStruct
{
int a;
const int b;
}

struct Range
{
MyStruct front;
void popFront()
{
front = MyStruct(2, 3);
}

enum empty = false;
}
---
This sample doesn't compile.


Re: D-Day for DMD is today!

2015-09-03 Thread Freddy via Digitalmars-d-announce

On Tuesday, 1 September 2015 at 15:48:42 UTC, Luís Marques wrote:
Exactly. I was surprised to find out I couldn't use Phobos in 
ddmd. Raw D is still more pleasant than programming in C++, but 
not nearly as much fun as writing normal D code.


Wait can the GC be used in ddmd?


Re: Object.factory() and exe file size bloat

2015-08-21 Thread Freddy via Digitalmars-d

On Friday, 21 August 2015 at 05:06:47 UTC, Walter Bright wrote:

This function:

  http://dlang.org/phobos/object.html#.Object.factory

enables a program to instantiate any class defined in the 
program. To make it work, though, every class in the program 
has to have a TypeInfo generated for it. This leads to bloat:

What do you think?


Can't we just make that Object.factory() an empty template and 
lazily instantiate class TypeInfo when needed.


Reading dmd's source code

2015-08-19 Thread Freddy via Digitalmars-d-learn
dmd's source code is very big, are there tips for reading 
it(important files)?


pragma(mangle, on a template)

2015-08-16 Thread Freddy via Digitalmars-d-learn

I can't get pragma(mangle) to work on templates(or structs).

import std.stdio;

struct MyStruct(T...)
{
int var;
void func()
{
writeln(var);
}
}

pragma(mangle, MyAlias) alias MyAlias = MyStruct!(a, b, c 
/+very long symbol bloating list+/ );


void main()
{
auto v = MyAlias(2);
v.func();
}



Re: Pointers to Dynamic Arrays

2015-08-16 Thread Freddy via Digitalmars-d-learn

On Monday, 17 August 2015 at 02:45:22 UTC, Brandon Ragland wrote:

if(file[(*pos + i)] == '}'){
*pos += i;
return;
}


That code doesn't do what you want it do. file is a ((char[])*) 
you are indexing the pointer(accessing invalid memory) and 
getting a char[].


Re: pragma(mangle, on a template)

2015-08-16 Thread Freddy via Digitalmars-d-learn

On Monday, 17 August 2015 at 03:14:16 UTC, Adam D. Ruppe wrote:

On Monday, 17 August 2015 at 02:46:02 UTC, Freddy wrote:
Mangling is done at a different level in the compiler than 
aliases, so I don't think this is intended to work.

Is there any way I can mangle a template struct then?


pragma(mangle) only works on functions

2015-08-16 Thread Freddy via Digitalmars-d
I felt this was important enough to big over to the D general 
chat.
Original 
Thread:http://forum.dlang.org/thread/zmmsodqrffvcdqidv...@forum.dlang.org


BBasile's Example:

On Monday, 17 August 2015 at 04:32:47 UTC, BBasile wrote:

On Monday, 17 August 2015 at 02:46:02 UTC, Freddy wrote:

I can't get pragma(mangle) to work on templates(or structs).
[...]


I don't know why but it looks like it only works on functions. 
Even if a struct is not a template the custom symbol mangle 
won't be handled:


---
import std.stdio;

pragma(mangle, a0) class MyClass{}
pragma(mangle, a1) struct MyStruct{}
pragma(mangle, a2) void body_func();
pragma(mangle, a3) struct MyStructh
{ pragma(mangle, a4) void foo(){}}

void main()
{
writeln(MyClass.mangleof);
writeln(MyStruct.mangleof);
writeln(body_func.mangleof);
writeln(MyStructh.mangleof);
writeln(MyStructh.foo.mangleof);
}
---

which outputs:

---
C13temp_019455687MyClass
S13temp_019455688MyStruct
a2
S13temp_019455689MyStructh
a4
---

'a4' being printed and not 'a3' is interesting BTW ;)
I think that the manual is not clear enough about this pragma:

http://dlang.org/pragma.html#mangle

Unless the spec. are more detailed this could be considered as 
a bug.





Indivisual Incremental Compalation with dub

2015-08-12 Thread Freddy via Digitalmars-d-learn
I have a file that takes a while to compile with a static 
interface. Is there any way i can make dub keep the object file 
of only that file(for faster compilation)?


[Semi OT] DDT Eclipse Plugin

2015-08-12 Thread Freddy via Digitalmars-d
I just install eclipse with the DDT 
plugin(https://ddt-ide.github.io/) and it worked well. It has 
auto complete, dub support(with a minor case senativity bug),and 
other IDE features.


Algebraic replacement

2015-07-08 Thread Freddy via Digitalmars-d
std.variant's Algebraic 
(https://github.com/D-Programming-Language/phobos/blob/master/std/variant.d) seems very complex for what it's trying to do and is also unsafe.


Is it worth writing a simpler replacement?

Something like this 
https://github.com/Superstar64/tagged_union/blob/master/source/tagged_union.d ?


Re: Algebraic replacement

2015-07-08 Thread Freddy via Digitalmars-d
On Wednesday, 8 July 2015 at 21:34:01 UTC, Andrei Alexandrescu 
wrote:

What's unsafe about it?


peek returns a pointer to a stack variable

import std.variant;
import std.stdio;

void main()
{
Algebraic!(int,string) a = a;
string* b = a.peek!string;
a = 0;
writeln(b.length);
}



Re: Algebraic replacement

2015-07-08 Thread Freddy via Digitalmars-d

On Wednesday, 8 July 2015 at 22:19:52 UTC, Freddy wrote:
On Wednesday, 8 July 2015 at 21:34:01 UTC, Andrei Alexandrescu 
wrote:

What's unsafe about it?

+ I meant that it can't be used in @safe code




copying const

2015-06-24 Thread Freddy via Digitalmars-d

I was surprised when this happened, is it a bug or a feature?

---
struct A
{
const int var;
}

int test()
{
auto b = A(5);
auto c = A(7);
pragma(msg, typeof(b)); //A
pragma(msg, typeof(c)); //A
auto d = b; //compiles
b = c; //doesn't compile
}
---
$ rdmd -main -unittest test
A
A
test.d(13): Error: cannot modify struct b A with immutable members
Failed: [dmd, -main, -unittest, -v, -o-, test.d, 
-I.]


Re: ReturnType and overloaded functions

2015-06-12 Thread Freddy via Digitalmars-d
I am curious about the answer myself but there is the 
workaround of passing the overload through a lambda:


import std.traits;

int foo(long)
{
return 0;
}

short foo(byte)
{
return 0;
}

void main()
{
static assert(is (ReturnType!(() = foo(long.init)) == 
int));
static assert(is (ReturnType!(() = foo(byte.init)) == 
short));

}

Ali


Why not just use templates?

int foo(size_t id)() if(id == 0){
return 0;
}

short foo(size_t id)() if(id == 1){
return 0;
}

static assert(is(typeof(foo!0()) == int));
static assert(is(typeof(foo!1()) == short));


ImplicitConversionTargets opposite

2015-05-21 Thread Freddy via Digitalmars-d-learn

std.traits has ImplicitConversionTargets.
Is there any template that returns the types that can implicty 
convert to T?


Type tuple pointers

2015-05-21 Thread Freddy via Digitalmars-d

Why don't pointers and .sizeof work with typetuples

import std.typetuple;
void main(){
TypeTuple!(int,char)* test;
TypeTuple!(long,int).sizeof;
}

$ rdmd test
test.d(3): Error: can't have pointer to (int, char)
test.d(4): Error: no property 'sizeof' for tuple '(long, int)'
Failed: [dmd, -v, -o-, test.d, -I.]

I know they can be wrapped in structs but shouldn't this work in 
the first place.


Associative array on the heap

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

How do you allocate an associative array on the heap?

void main(){
alias A=int[string];
auto b=new A;
}

$ rdmd test
test.d(4): Error: new can only create structs, dynamic arrays or 
class objects, not int[string]'s

Failed: [dmd, -v, -o-, test.d, -I.]


Re: Associative array on the heap

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

On Tuesday, 19 May 2015 at 00:00:30 UTC, Meta wrote:

On Monday, 18 May 2015 at 23:55:40 UTC, Freddy wrote:

How do you allocate an associative array on the heap?

void main(){
alias A=int[string];
auto b=new A;
}

$ rdmd test
test.d(4): Error: new can only create structs, dynamic arrays 
or class objects, not int[string]'s

Failed: [dmd, -v, -o-, test.d, -I.]


They are allocated on the heap implicitly; there's no need for 
`new`. You actually *can't* use new with an AA, which is what 
the compiler is telling you.


void main()
{
alias A = int[string];
A b = []; //No allocation yet, b is null
b[test] = 1; //b is now non-null
}


Sorry mis-phrased my question,
 Who do you allocate a pointer to an associative 
array(int[string]*).


Re: Good examples of value types

2015-05-06 Thread Freddy via Digitalmars-d

On Tuesday, 5 May 2015 at 20:40:59 UTC, Luís Marques wrote:

Hi,

For a comparison with the Java language, I'm trying to come up 
with some good examples of custom types that should be value 
types (but that must be ref types in Java). I think the most 
obvious ones are numeric types. So BigNum, MyNum, etc. are good 
examples because programmers are used to numeric types being 
value types, and having them suddenly become a ref type just 
because it's MyNum instead of long is really annoying. Still, 
could you come up with some type that would really benefit from 
being a value type but that isn't numeric (or otherwise 
similar)?


Thanks for your help!

Luís

Immutable types?
It doesn't matter whether they are by value or by ref but by 
value usually has performance increases(especially considering 
you can by a value type by ref in D if you need to).


Re: Adding a read primitive to ranges

2015-05-05 Thread Freddy via Digitalmars-d
How would it be more optimal? As I said, if you pass in 
`file.byChunks(some_amount).joiner`, this will still read the 
file in large chunks. It's less optimal now because `read` has 
to allocate an array on every call (easily avoidable by passing 
in a reusable buffer, but still).


Equivalent code with ranges:

auto range = file.byChunks(4096).joiner;
ubyte[] data = range.take(VERY_BIG_NUMBER).array;
ubyte[] other_data = 
range.take(OTHER_VERY_BIG_NUMBER).array;


The range solution copies from a buffer to a newly allocated 
array many times, doing many system calls.
The read(stream) solution allocates a new array and does one 
system call.


Sorry for the miscommunication.


std.mmfile is broken

2015-05-05 Thread Freddy via Digitalmars-d
The garbage collector is not required to call class destructors, 
but Mmfile is a class and could leak memory.

http://dlang.org/phobos/std_mmfile.html


Re: Adding a read primitive to ranges

2015-05-04 Thread Freddy via Digitalmars-d

On Monday, 4 May 2015 at 15:16:25 UTC, Alex Parrill wrote:


IT seems redundant to me. It's semantically no different than 
iterating through the range normally with front/popFront. For 
objects where reading large amounts of data is more efficient 
than reading one-at-a-time, you can implement a byChunks 
function like stdio.File.


The ploblem is that all the functions in std.range,std.algorithm 
and many other wrappers would ignore byChucks and produce much 
slower code.


Re: Adding a read primitive to ranges

2015-05-04 Thread Freddy via Digitalmars-d

On Monday, 4 May 2015 at 00:07:27 UTC, Freddy wrote:
Would it be a bad idea to add a read primitive to ranges for 
streaming?


struct ReadRange(T){
size_t read(T[] buffer);
//and | or
T[] read(size_t request);

/+ empty,front,popFront,etc +/
}



Also if so, What about adding a default read for input ranges.
Something like

typeof(range.front)[] read(R)(ref R range,size_t amount){
auto data=new typeof(range.front)[amount];
/+... read into data ...+/
return data[0..actual_amount];
}



Re: Adding a read primitive to ranges

2015-05-04 Thread Freddy via Digitalmars-d

On Monday, 4 May 2015 at 23:20:57 UTC, Alex Parrill wrote:

On Monday, 4 May 2015 at 19:23:08 UTC, Freddy wrote:

On Monday, 4 May 2015 at 15:16:25 UTC, Alex Parrill wrote:

The ploblem is that all the functions in 
std.range,std.algorithm and many other wrappers would ignore 
byChucks and produce much slower code.


How so? `file.byChunks(4096).joiner` is a range that acts as if 
you read each byte out of the file one at a time, but actually 
reads them in 4096-byte buffers. It's still compatible with all 
of the range and algorithm functions.


Reading an arbitrary number of data after being wrapped.
For example

void func(R)(R range){//expects range of strings
string[] elms=range.read(5);
string[] elms2=range.read(9);
/++..++/
}


void caller(){
auto file=...;//unbuffered file
file.map!(a=a.to!string).func();
}

Using byChucks would cause much more reallocation.


Re: Adding a read primitive to ranges

2015-05-04 Thread Freddy via Digitalmars-d

On Tuesday, 5 May 2015 at 00:50:44 UTC, Freddy wrote:


void func(R)(R range){//expects range of strings
string[] elms=range.read(5);
string[] elms2=range.read(9);
/++..++/
}


void caller(){
auto file=...;//unbuffered file
file.map!(a=a.to!string).func();
}


Wait, Bad example,

void func(R)(R range){//expects range of ubyte
ubyte[] data=range.read(VERY_BIG_NUMBER);
ubyte[] other_data=range.read(OTHER_VERY_BIG_NUMBER);
}

which would be more optimal for a file but still works for other 
ranges, compared to looping though the ranges read appending to 
data.


Adding a read primitive to ranges

2015-05-03 Thread Freddy via Digitalmars-d
Would it be a bad idea to add a read primitive to ranges for 
streaming?


struct ReadRange(T){
size_t read(T[] buffer);
//and | or
T[] read(size_t request);

/+ empty,front,popFront,etc +/
}



compile time garbage collection

2015-05-02 Thread Freddy via Digitalmars-d
How crazy hard would it be to have a front end optimization pass 
that would try to replace garbage collector calls with malloc / 
free?


Closure capture loop variables

2015-04-29 Thread Freddy via Digitalmars-d

I understand that

import std.stdio;
void main(){
int delegate() func;
foreach(i;0..10){
if(i==5){
func= () = i;
}
}
writeln(func());//9
}

captures the loop variable,but why does

import std.stdio;

void main(){
int delegate() func;
foreach(i;0..10){
auto copy=i;
if(i==5){
func= () = copy;
}
}
writeln(func());//should be 5
}


still print 9.


Re: Closure capture loop variables

2015-04-29 Thread Freddy via Digitalmars-d
On Thursday, 30 April 2015 at 01:19:45 UTC, Vladimir Panteleev 
wrote:

Because copy is still modified every time i is.
But shouldn't copy be redeclared every loop iteration (or the 
compiler could pretend to redeclare it).


Re: Adding pointers to GC with destructers

2015-04-20 Thread Freddy via Digitalmars-d-learn

On Monday, 20 April 2015 at 02:56:35 UTC, Ali Çehreli wrote:

Not automatically. Check out addRange and addRoot:

  http://dlang.org/phobos/core_memory.html

Ali

The destructor doesn't seem to be running

import std.stdio;
import std.c.stdlib;
import core.memory;
struct Test{
~this(){
writeln(free: ,this);
free(this);
}
}

void main(){
auto ptr=cast(Test*)malloc(4);
writeln(create: ,ptr);
GC.addRange(ptr,0,typeid(Test));
ptr=null;
GC.collect();
}

$ rdmd test
create: 1EEC730


Re: Adding pointers to GC with destructers

2015-04-20 Thread Freddy via Digitalmars-d-learn

On Monday, 20 April 2015 at 22:24:53 UTC, Ali Çehreli wrote:

On 04/20/2015 02:48 PM, Freddy wrote:

On Monday, 20 April 2015 at 02:56:35 UTC, Ali Çehreli wrote:

Not automatically. Check out addRange and addRoot:

 http://dlang.org/phobos/core_memory.html

Ali

The destructor doesn't seem to be running


Sorry, I misunderstood you. You can use a RAII object as ketmar 
said:


import std.stdio;
import std.c.stdlib;

struct Test{
void* ptr;

~this(){
writeln(free: ,this);
free(ptr);
}
}

void main(){
auto ptr=cast(Test*)malloc(4);
writeln(create: ,ptr);

auto test = Test(ptr);  // -- The dtor of this object will 
free

}

Ali
I believe your original understanding was right.I want to have 
HiddenType* be garbage collected and finalized(freed,destructed) 
when no more references to it are found(stack or heap). I could 
use reference counting but it seems inefficient for a program 
rarely collecting and constantly coping.


Adding pointers to GC with destructers

2015-04-19 Thread Freddy via Digitalmars-d-learn

C libraries have a pattern of

HiddenType* getObj();
void freeObj(HiddenType*);

Is there any way I can make the GC search for a HiddenType* and 
run freeObj when the pointer is not found.


UFCS overrides alias this

2015-04-12 Thread Freddy via Digitalmars-d


test.d
struct A{
string b;
alias b this;
}

struct MyRange{

}
char front(MyRange);
void popFront(ref MyRange);
bool empty(MyRange);

void test(A a){
a.empty;
}

$ dmd -o- test
test.d(14): Error: function test.empty (MyRange) is not callable 
using argument types (A)


Is this intended behavior?


Re: UFCS overrides alias this

2015-04-12 Thread Freddy via Digitalmars-d

On Sunday, 12 April 2015 at 20:35:06 UTC, anonymous wrote:
string's empty is actually a function in std.array or std.range 
or something, called via UFCS. You don't import std's empty, so 
the call can't match even when the alias this is tried.


Add the following, which brings std's empty into the overload 
set, and it works:


static import std.range;
alias empty = std.range.empty;

test.d
static import std.range;
alias empty=std.range.empty;
struct A{
string b;
alias b this;
}

struct MyRange{

}
char front(MyRange);
void popFront(ref MyRange);
bool empty(MyRange);

void test(A a){
a.empty;
}

$ dmd -o- test
test.d(16): Error: overload alias 'empty' is not a variable

No idea what dmd is doing.

However it works with

private auto empty(string s){
static import std.range;
return std.range.empty(s);
}



Re: Filling out the wiki - D as a second language

2015-04-02 Thread Freddy via Digitalmars-d

On Tuesday, 31 March 2015 at 22:25:29 UTC, rumbu wrote:
Unfortunately, I cannot edit directly on wiki.dlang.org since 
my account is not confirmed (confirmation e-mail is not sent 
despite several attempts).
By any chance, do you use gmail? The email sent by the wiki 
appeared in my gmail's spam.


final switch on Algebraic

2015-03-29 Thread Freddy via Digitalmars-d-learn
Is there any way to do a final switch statement in std.variant's 
Algebraic.


Re: Can we deprecate D-style Variadic Functions

2015-03-27 Thread Freddy via Digitalmars-d

On Friday, 27 March 2015 at 20:57:51 UTC, Freddy wrote:

template VariadicFunction(alias Imp){
auto VariadicFunction(T...)(T args){
void* data=args;
TypeInfo[T.length] rtti;
foreach(i,type;T){
rtti[i]=typeid(type);
}
Imp(data,rtti);
}
}
```
I haven't looked in dmd's source yet but doesn't the compiler 
have to do (an inlined version of) this anyway for runtime 
variadic functions.


Re: Can we deprecate D-style Variadic Functions

2015-03-27 Thread Freddy via Digitalmars-d

On Friday, 27 March 2015 at 19:59:13 UTC, deadalnix wrote:
To be fair, this is most likely going to be inlined an ditched 
away with any decent optimizer.


It wouldn't even need alloca if sizeof and address of worked with 
tuples.

```
template VariadicFunction(alias Imp){
auto VariadicFunction(T...)(T args){
void* data=args;
TypeInfo[T.length] rtti;
foreach(i,type;T){
rtti[i]=typeid(type);
}
Imp(data,rtti);
}
}
```


Can we deprecate D-style Variadic Functions

2015-03-25 Thread Freddy via Digitalmars-d
D-style Variadic Functions found 
here:http://dlang.org/function.html seem entirely out classed by 
Variadic Function Templates. Can we deprecate them?


Re: Can we deprecate D-style Variadic Functions

2015-03-25 Thread Freddy via Digitalmars-d

On Thursday, 26 March 2015 at 00:11:05 UTC, Dicebot wrote:

On Wednesday, 25 March 2015 at 22:12:04 UTC, Freddy wrote:
D-style Variadic Functions found 
here:http://dlang.org/function.html seem entirely out classed 
by Variadic Function Templates. Can we deprecate them?


Those are two different concepts with different trade-offs. 
Using variadic templates adds template bloat. Using D-style 
variadics requires RTTI (and small overhead for it). It is up 
to library/application writer to decide what is best in his 
case.


My ploblem is that Variadic Function shouldn't be builtin the 
language. They are rarely need and can be abstracted into a 
library. Something like this:

```
import core.stdc.stdlib: alloca;
import std.stdio;
template VariadicFunction(alias Imp){
auto VariadicFunction(T...)(T args){
enum size=T.length * TypeInfo.sizeof;
auto rtti=cast(TypeInfo[])(alloca(size)[0..size]);
foreach(i,type;T){
rtti[i]=typeid(type);
}
//auto data=args; bug? doesn't work
void* data;
{
size_t datasize;//T.sizeof doesn't work
foreach(type;T){
datasize+=type.sizeof;
}
data=alloca(datasize);
size_t inc;
foreach(v;args){
*cast(typeof(v)*)(data+inc)=v;
inc+=v.sizeof;
}
}
Imp(data,rtti);
}
}

private void rtVariadicImp(void* vars,scope const TypeInfo[] 
rtinfo){

writeln(*cast(int*)vars);
writeln(rtinfo);
}

alias rtVariadic=VariadicFunction!(rtVariadicImp);

void main(){
rtVariadic(1,'a');
}
```


Re: A few notes on choosing between Go and D for a quick project

2015-03-12 Thread Freddy via Digitalmars-d

On Friday, 13 March 2015 at 02:17:31 UTC, bearophile wrote:

A strict D mode?


That sounds like an amazing idea.


Typi, Simple compile to javascript toy language

2015-03-04 Thread Freddy via Digitalmars-d-announce

I got bored and made this
https://github.com/Superstar64/typi


Re: Standard GUI framework inspired by Qt

2015-03-03 Thread Freddy via Digitalmars-d

On Tuesday, 3 March 2015 at 18:43:50 UTC, Aram wrote:

Hi all

I've been thinking over a GUI framework for D for some time, 
and ended up with idea expressed by Andrew Fedoniouk here: 
http://www.digitalmars.com/d/archives/digitalmars/D/32633.html. 
That is, having a separate drawing layer, and widgets built on 
top of it. But since it has already been discussed 9 years ago, 
I wonder if such a framework has ever been implemented.


In that duscussion many participants agreed that Qt would be a 
good foundation, but had very restrictive license. Things have 
changed since then, and Qt now is available under LGPL, which, 
to my undestanding, makes it suitable for the purpose of 
standard GUI library (please correct me if I am wrong on this). 
The license, of course, may change in the future, preventing us 
from using their updates for our drawing engine. But if we are 
able to start using the engine now, in the future we can 
maintain the updates ourselves.


Now, how I envision the library's design:

The library will be mostly implemented in D, except for drawing 
engine and event loop, which are system-dependent. Those two 
parts will be extracted from Qt into a separate library which 
will be linked to by the rest of framework either statically or 
dynamically. There will be bindings for sending drawing 
instructions to drawing engine, as well as for retrieving 
system and GUI events from event loop.


The system-independent part will mimic architecture of Qt. 
However, for maximum flexibility and customizability, GUI will 
utilize QML+CSS approach, and Qt's layout manager classes will 
be dropped completely. Also there is no need to port classes 
that are available in D, such as collections and strings.



If there is no standard GUI for D yet, and if LGPL license fits 
our purpose, then I am looking for 2-3 Qt experts to join me 
and build the framework.


Thanks,
Aram
I'm not much of a gui person,but what is the advantage of using 
QML over D's import 
statements(http://dlang.org/expression.html#ImportExpression) and 
CTFE.


Re: Standard GUI framework inspired by Qt

2015-03-03 Thread Freddy via Digitalmars-d

On Tuesday, 3 March 2015 at 22:16:36 UTC, Freddy wrote:

On Tuesday, 3 March 2015 at 18:43:50 UTC, Aram wrote:

Hi all

I've been thinking over a GUI framework for D for some time, 
and ended up with idea expressed by Andrew Fedoniouk here: 
http://www.digitalmars.com/d/archives/digitalmars/D/32633.html. 
That is, having a separate drawing layer, and widgets built on 
top of it. But since it has already been discussed 9 years 
ago, I wonder if such a framework has ever been implemented.


In that duscussion many participants agreed that Qt would be a 
good foundation, but had very restrictive license. Things have 
changed since then, and Qt now is available under LGPL, which, 
to my undestanding, makes it suitable for the purpose of 
standard GUI library (please correct me if I am wrong on 
this). The license, of course, may change in the future, 
preventing us from using their updates for our drawing engine. 
But if we are able to start using the engine now, in the 
future we can maintain the updates ourselves.


Now, how I envision the library's design:

The library will be mostly implemented in D, except for 
drawing engine and event loop, which are system-dependent. 
Those two parts will be extracted from Qt into a separate 
library which will be linked to by the rest of framework 
either statically or dynamically. There will be bindings for 
sending drawing instructions to drawing engine, as well as for 
retrieving system and GUI events from event loop.


The system-independent part will mimic architecture of Qt. 
However, for maximum flexibility and customizability, GUI will 
utilize QML+CSS approach, and Qt's layout manager classes will 
be dropped completely. Also there is no need to port classes 
that are available in D, such as collections and strings.



If there is no standard GUI for D yet, and if LGPL license 
fits our purpose, then I am looking for 2-3 Qt experts to join 
me and build the framework.


Thanks,
Aram
I'm not much of a gui person,but what is the advantage of using 
QML over D's import 
statements(http://dlang.org/expression.html#ImportExpression) 
and CTFE.

*import expression.


strings and array literal mutability

2015-02-24 Thread Freddy via Digitalmars-d-learn

Why are strings immutable but array literals are not?


Comparing function pointers

2015-02-11 Thread Freddy via Digitalmars-d-learn


import std.stdio;

auto test1(){
void testFunc(){
}
return testFunc;
}

auto test2(){
uint a;
void testFunc(){
a=1;
}
return testFunc;
}

void main(){
writeln(test1()==test1());//true
writeln(test2()==test2());//false
}

Is the intended behavior?


Re: forcing @nogc on class destructors

2015-01-20 Thread Freddy via Digitalmars-d
On Tuesday, 20 January 2015 at 18:12:27 UTC, ketmar via 
Digitalmars-d wrote:

Hello.

as there is no possibility to doing GC allocations in class
destructors, wouldn't it be nice to just force @nogc 
attribute on

such dtors?

i know, i know, this will break alot of code. i'm pretty sure 
that

this will break alot of INVALID code, which better be broken at
compile-time anyway.

sure, we have alot of code of pre-@nogc era, and alot of code 
where
authord didn't bother to add attributes at all. so we can 
introduce
--force-dtor-nogc CLI arg and document this change, making it 
opt-in

for, say, six month and opt-out after that.

and i know that D devs (Walter at least) are resistant to 
command-line
flags that changing compiler behavior. i don't know how to 
overcome
this. say, by adding @gc attribute, which dfix can 
automatically add?


but i still believe that instead of telling people again and 
again that
they should not allocate in class destructors, we can use 
computer

itself to track and stop this behavior.

let's see how this proposal will be rejected. will there be 
some sane
reasons, or only the good old song about broken code? make 
your bets!

Not an error, Make it a warning.


Re: Improving ddoc

2014-12-31 Thread Freddy via Digitalmars-d
On Wednesday, 31 December 2014 at 21:51:32 UTC, ketmar via 
Digitalmars-d wrote:

On Wed, 31 Dec 2014 11:50:51 -0800
Andrei Alexandrescu via Digitalmars-d 
digitalmars-d@puremagic.com

wrote:

In wake of the recent discussions on improving ddoc syntax 
we're looking at doing something about it. Please discuss any 
ideas you might have here. Thanks!


ahem... kill it and use markdown instead.


http://commonmark.org/


Re: problem with size_t and an easy solution

2014-12-07 Thread Freddy via Digitalmars-d

On Monday, 8 December 2014 at 01:30:35 UTC, ketmar via
Digitalmars-d wrote:

Hello.

i don't like `size_t`. for many month i avoied using it 
wherever that
was possible, 'cause i feel something wrong with it. and today 
i found

the soultion!

let's see how other D types are named: `int`, `uint`, `byte` 
(oh, well,

this name sux), `ulong`. see the pattern? so i decided to rename
`size_t` to `usize`. and you know what? it immidiately started 
to be
familiar. like a thing that was always here, simply dressed in 
patches.


let's face it: that ugly '_t' is alien to D. this is an ugly 
leftover
from C, and this leftover is nonsence. it will not really help 
anyone,
but it immideately turns D code to badly-looking crap. see for 
yourself:


  size_t countSomeElements();

and

  usize countSomeElements();

`size_t` looking like an alien here, ruining all the style.

i propose to introduce `usize` and `sptrdiff` along with those 
'_t'

uglyness, and then slowly migrate all the code to the new names.

yes, this is another cosmetic issue, but let me tell you that 
such

purely cosmetic things are really important for those who just
starting to learn the language.

it's impossible to write nice D code with `size_t`: we have 
either
alias it each time or use `uint`/`ulong` to make our code looks 
good.


really, i've seen people who using `uint` instead of `size_t`, 
'cause
with size_t my code looks ugly, and i tired of aliasing that 
shit
every time. ah, yep, their code sux for 64 bits, but: i know 
that

64-bit size_t is... 64-bit. i'll fix that later, maybe.

uglyness leads to bad code. let's kill `size_t` for good!


p.s. some of you may think that i'm trolling. i can assure you 
that
this post is not trolling, this is just another try to talk 
about
purely cosmetic issues and how they hurts the language, 
especially

for beginners. when beginner see such pure cosmetic issue, he
starting to think that the whole language is a mess: hey, this 
is such
easy to fix, but they never bother to... i bet the other parts 
of the
language are even worse. and you know what? it's enough to 
make such
mistake two or three times to make people believe that D is a 
dirty
and hackish language without clear style. this is gly is 
*the*

*argument*.


I would like if usize wasn't implictly convertable to uint or
ulong


Re: problem with size_t and an easy solution

2014-12-07 Thread Freddy via Digitalmars-d

On Monday, 8 December 2014 at 02:04:58 UTC, ketmar via
Digitalmars-d wrote:

On Mon, 08 Dec 2014 01:50:44 +
Freddy via Digitalmars-d digitalmars-d@puremagic.com wrote:


I would like if usize wasn't implictly convertable to uint or
ulong
me too, but this change is too radical. it will not break any 
of my
own code ('cause i used to write casts for that stupid 64-bit 
systems to
shut up), but i doubt that other people will agree with such 
change.


Why not keep size_t implictly convertable but disallow it for
usize.


Re: std::string responsible for half the allocations in chrome

2014-12-06 Thread Freddy via Digitalmars-d

On Saturday, 6 December 2014 at 16:10:20 UTC, Joseph Rushton
Wakeling via Digitalmars-d wrote:

On 05/12/14 23:03, deadalnix via Digitalmars-d wrote:

http://www.reddit.com/r/programming/comments/2ocmvb/stdstring_is_responsible_for_almost_half_of_all/

Looks like someone need immutable(char)[] .


Someone asked me the other day, and I realized I didn't have a 
ready answer as I'd never particularly considered it: why is it 
important/beneficial that the string type be immutable(char)[] ?


Because string literals must be in the read only part of the
program.


void test()
{
 string s=abc;
 callFunc(s);
 s[0]='z'//next call to test will set a=zbc
}


Otherwise the compiler would have to create a copy everytime you
assign a string literal to variable(call .dub for you).


Re: Do everything in Java…

2014-12-05 Thread Freddy via Digitalmars-d

On Thursday, 4 December 2014 at 13:48:04 UTC, Russel Winder via
Digitalmars-d wrote:
It's an argument for Java over Python specifically but a bit 
more

general in reality. This stood out for me:


!…other languages like D and Go are too new to bet my work on.


http://www.teamten.com/lawrence/writings/java-for-everything.html


My problems with java:
  no unsigned ints
  primitive are passed by value; arrays and user defined types are
passed by reference only (killing memory usage)
  no operator overloading(looks at java.util.ArrayList)
  no templates
  no property syntax(getters and setters are used instead even if
you know the field is never going to be dynamic)
  only and exactly one class per file(ALL THE IMPORTS)
  every thing must be inside a class(globals and free functions
are static fields in a class)
This is all i can remember.


Why does hello world not compile in safe?

2014-11-28 Thread Freddy via Digitalmars-d-learn


import std.stdio;
@safe:
void main()
{
writeln(Edit source/app.d to start your project.);
}


source/app.d(5): Error: safe function 'D main' cannot call system
function 'std.stdio.writeln!(string).writeln'


How does this work?

2014-11-23 Thread Freddy via Digitalmars-d-learn

I know what this does, but can someone explain how it works?

static if((typeof((inout int=0){

})));



Re: size_t for length on x64 will make app slower than on x86?

2014-11-17 Thread Freddy via Digitalmars-d

On Monday, 17 November 2014 at 15:28:52 UTC, FrankLike wrote:

I test it:

module aasize_t;
import std.stdio;
import std.datetime;
import std.conv;
import std.string;

size_t[string] aa;

void gettime()
{
for(size_t i=0;i300;i++)
{
aa[to!string(i)] = i;
}
}
void main()
{   writeln(size_t.max,size_t.max);
gettime();
void getlen(){auto alne = aa.length;}
auto r = benchmark!(getlen)(1);
	auto f0Result = to!Duration(r[0]); // time f0 took to run 
10,000 times

writeln(\n size_t time is :,f0Result);
StopWatch sw;
sw.start();
gettime();
sw.stop();
writeln(\n size_t time is sw:,sw.peek.msecs, msecs);
}
--and anoter is uint[string] aa

dmd -m64 aauint.d
dmd -m64 aasize_t.d
dmd aaint.d -ofaauint32.exe
dmd aasize_t.d -ofaasize_t32.exe

@del *.obj

aaint
aasize_t

aaint32
aasize_t32
@pause

Last Result:

They take the almost same time,and usage memory. but uint(or 
int) is more practical for length to use.

Don't profile with out optimzation.
Add -O -inline -release -boundscheck=off to your dmd arguments.


Re: Scope and Ref and Borrowing

2014-11-17 Thread Freddy via Digitalmars-d

On Friday, 14 November 2014 at 01:21:07 UTC, Walter Bright wrote:
Thought I'd bring this up as deadalnix is working on a related 
proposal. It uses 'scope' in conjunction with 'ref' to resolve 
some long standing @safe issues.

---

**Background

The goal of @safe code is that it is guaranteed to be memory 
safe. This is mostly
achieved, but there's a gaping hole - returning pointers to 
stack objects when those

objects are out of scope. This is memory corruption.

The simple cases of this are disallowed:

  T* func(T t) {
T u;
return t; // Error: escaping reference to local t
return u; // Error: escaping reference to local u
  }

But are is easily circumvented:

  T* func(T t) {
T* p = t;
return p;  // no error detected
  }

@safe deals with this by preventing taking the address of a 
local:


  T* func(T t) @safe {
T* p = t; // Error: cannot take address of parameter t in 
@safe function func

return p;
  }

But this is awfully restrictive. So the 'ref' storage class was 
introduced which
defines a special purpose pointer. 'ref' can only appear in 
certain contexts,
in particular function parameters and returns, only applies to 
declarations,

cannot be stored, and cannot be incremented.

  ref T func(T t) @safe {
return t; // Error: escaping reference to local variable t
  }

Ref can be passed down to functions:

  void func(ref T t) @safe;
  void bar(ref T t) @safe {
 func(t); // ok
  }

But the following idiom is far too useful to be disallowed:

  ref T func(ref T t) @safe {
return t; // ok
  }

And if it is misused it can result in stack corruption:

  ref T foo() @safe {
T t;
return func(t); // no error detected, despite returning 
pointer to t

  }

The purpose of this proposal is to detect these cases at 
compile time and disallow them.
Memory safety is achieved by allowing pointers to stack objects 
be passed down the stack,
but those pointers may not be saved into non-stack objects or 
stack objects higher on the stack,

and may not be passed up the
stack past where they are allocated.

The:

return func(t);

case is detected by all of the following conditions being true:

1. foo() returns by reference
2. func() returns by reference
3. func() has one or more parameters that are by reference
4. 1 or more of the arguments to those parameters are stack 
objects local to foo()
5. Those arguments can be @safe-ly converted from the parameter 
to the return type.
   For example, if the return type is larger than the parameter 
type, the return type
   cannot be a reference to the argument. If the return type is 
a pointer, and the
   parameter type is a size_t, it cannot be a reference to the 
argument. The larger
   a list of these cases can be made, the more code will pass 
@safe checks without requiring

   further annotation.

**Scope Ref

The above solution is correct, but a bit restrictive. After 
all, func(t, u) could be returning
a reference to non-local u, not local t, and so should work. To 
fix this, introduce the concept

of 'scope ref':

ref T func(scope ref T t, T u) @safe {
  return t; // Error: escaping scope ref t
  return u; // ok
}

Scope means that the ref is guaranteed not to escape.

  T u;
  ref T foo() @safe {
T t;
return func(t, u); // ok, u is not local
return func(u, t); // Error: escaping scope ref t
  }

This scheme minimizes the number of 'scope' annotations 
required.


**Out Parameters

'out' parameters are treated like 'ref' parameters for the 
purposes of this document.


**Inference

Many functions can infer pure, @safe, and @nogc. Those same 
functions can infer
which ref parameters are 'scope', without needing user 
annotation.


**Mangling

Scope will require additional name mangling, as it affects the 
interface of the function.


**Nested Functions

Nested functions have more objects available than just their 
arguments:


  ref T foo() @safe {
T t;
ref T func() { return t; }
return func();  // should be disallowed
  }

On the plus side the body of the nested function is available 
to the compiler for

examination.

**Delegates and Closures

This one is a little harder; but the compiler can detect that t 
is taken by reference,
and then can assume that dg() is returning t by reference and 
disallow it.


  ref T foo() @safe {
T t;
ref T func() { return t; }
auto dg = func;
return dg();  // should be disallowed
  }


**Overloading

Scope does not affect overloading, i.e.:

   T func(scope ref a);
   T func(ref T b);

are considered the same as far as overloading goes.

**Inheritance

Overriding functions inherit any 'scope' annotations from their 
antecedents.


**Limitations

Arrays of references are not allowed.
Struct and class fields that are references are not allowed.
Non-parameter variables cannot be references.


Why not make the compiler copy the variable how's address is
taken to the heap like how a closure 

  1   2   >