Re: construct range from tuple?

2016-09-18 Thread Lutger via Digitalmars-d-learn

On Sunday, 18 September 2016 at 09:36:13 UTC, e-y-e wrote:

On Sunday, 18 September 2016 at 08:06:54 UTC, Lutger wrote:

[...]


Use std.range's 'only' function [1], it takes variadic 
arguments of the same type and constructs a range consisting of 
them.


Example:

import std.meta : AliasSeq;
import std.range : only;
import std.algorithm.comparison : equal;

alias names = AliasSeq!("Alice", "Bob");

auto range = only(names, "Chuck");
assert(range.equal(["Alice", "Bob", "Chuck"]));


That's *exactly* what I was looking for, thanx!


Re: Can vibe d leverage existing web technologies?

2016-09-18 Thread Lutger via Digitalmars-d-learn
On Thursday, 15 September 2016 at 20:56:19 UTC, Intersteller 
wrote:
On Thursday, 15 September 2016 at 14:31:28 UTC, Martin 
Tschierschke wrote:
On Tuesday, 13 September 2016 at 23:45:18 UTC, Intersteller 
wrote:
vibe.d does not have much lateral support as the most commons 
web technologies do.  Can vibe.d leverage pre-existing techs 
such as php, ruby/rails, etc? Starting from scratch and 
having to build a robust and secure framework is really not 
the way to go.


A good way to mix different technologies is to use a Apache or 
nginx proxy on the same server, so you can start using vibe.d 
for some parts and keep the rest at its place.


Regards mt.


How is this done? How can it be done smoothly? I'm not sure how 
to partition the work load. While, say, some pages might be 
served from php, and others from vibe2, etc, it seems like it 
would be nightmare to maintain consistency and interactivity.


True. It is easier to maintain if you do a 'vertical split'. So 
each subsystem maintains a strict boundary. You have to be clear 
about the dependencies between subsystems and any data exchange 
should happen via an explicit api. So there is no shared database 
between the D part and the php part for example. Communication 
with json over http is common and well supported by vibe.d. See: 
http://martinfowler.com/articles/microservices.html


This a more coarse grained approach which reduces coupling 
between the different parts.


For example, you could write a small api with vibe.d which does 
image processing, or collects and manipulates data from third 
party apis, or whatever. The rails app handles authentication and 
ui, making use of the services that your vibe.d api provides.


Another example: if you have a reasonably standalone part of a 
webapplication such as administrative pages or whatever, you 
could program that in vibe.d and let an nginx server route 
everything /admin/* to that part. The rails app exposes an api to 
modify its data which the admin app build in vibe.d makes use of.


construct range from tuple?

2016-09-18 Thread Lutger via Digitalmars-d-learn

I have a tuple of strings generated at compile time, for example:

  alias names = AliasSeq!("Alice", "Bob");

How is it possible to construct a range of strings from this, in 
order to use it at runtime with other range algorithms?


For example, this

  chain(names, ["Chuck"])

doesn't work as intended because it expands to

  chain("Alice", "Bob", ["Chuck"])

I want some function makeRange that works like this:

assert(chain(makeRange(names), ["Chuck"]).fold!( (x,y) => x ~ " " 
~ y) ==

   "Alice Bob Chuck");

What would be a good way to do that?







Equivalent of FirstOrDefault with ranges

2016-09-02 Thread Lutger via Digitalmars-d-learn
I was looking for something like FirstOrDefault* from .NET in 
phobos. For example, I have this piece of code:


string findBobOrReturnNull(string[] names)
{
auto r = names.find("bob");
if(r.empty) return null;
return r.front;
}

assert(findBobOrReturnNull(["alice", "bob"]) == "bob");
assert(findBobOrReturnNull(["alice"]) is null);

How can I turn that into something like this, or is there another 
idiomatic way to write it as a single expression?


string findBobOrReturnNull(string[] names)
{
return names.find("bob").firstOrDefault;
}

* 
https://msdn.microsoft.com/en-us/library/bb340482%28v=vs.110%29.aspx





Re: Simple I know, but could use some help compiling with make

2011-10-01 Thread Lutger Blijdestijn
Roderick Gibson wrote:

... 
> Hmm, looks like it would be awesome, unfortunately it spits out a bunch
> of "previous definition different" errors on the linker, in relation to
> the libraries. Oh well, I seem to be able to get it working with dmd for
> now.

This could be caused by having two 'main' functions in all the modules that 
rdmd finds.


Re: Any way to expand a tuple?

2011-09-25 Thread Lutger Blijdestijn
Andrej Mitrovic wrote:

> import std.typetuple;
> import std.typecons;
> 
> struct Foo
> {
> void test(int x, double y) { }
> 
> void opOpAssign(string op, T...)(T t)
> if (op == "~")
> {
> test(t);
> }
> }
> 
> void main()
> {
> Foo foo;
> foo.opOpAssign!"~"(4, 5.0);  // ok
> foo ~= tuple(4, 5.0);  // fail
> }
> 
> If I understand this correctly in the first call T becomes a D
> language tuple, while in the second one it's a phobos library tuple. I
> really hate this distinction and would love these two to be merged so
> the second call could compile.

.expand on Tuple and generally .tupleof does the trick. Language tuples are 
quite different and more general than typecons Tuple. If tuples would 
automatically expand, this would not be possible:

import std.typetuple;
import std.typecons;
import std.stdio;

struct Foo
{
void test(Tuple!(int, int), double y) { writeln("overload a"); }
void test(int, int, double y) { writeln("overload b"); }

void opOpAssign(string op, T...)(T t)
if (op == "~")
{
test(t);
}
}

void main()
{
Foo foo;
foo.opOpAssign!"~"(tuple(4, 2), 5.0);// overload a
foo.opOpAssign!"~"(tuple(4, 2).tupleof, 5.0);// overload b
}


Re: Multithreaded file IO?

2011-09-25 Thread Lutger Blijdestijn
Jerry Quinn wrote:

> Jonathan M Davis Wrote:
> 
>> On Saturday, September 24, 2011 01:05:52 Jerry Quinn wrote:
>> > Jonathan M Davis Wrote:
>> > > On Friday, September 23, 2011 23:01:17 Jerry Quinn wrote:
>> > > 
>> > > A direct rewrite would involve using shared and synchronized (either
>> > > on the class or a synchronized block around the code that you want to
>> > > lock). However, the more idiomatic way to do it would be to use
>> > > std.concurrency and have the threads pass messages to each other
>> > > using send and receive.
>> > 
>> > I'm trying the direct rewrite but having problems with shared and
>> > synchronized.
>> > 
>> > class queue {
>> >   File file;
>> >   this(string infile) {
>> > file.open(infile);
>> >   }
>> >   synchronized void put(string s) {
>> > file.writeln(s);
>> >   }
>> > }
>> > 
>> > queue.d(10): Error: template std.stdio.File.writeln(S...) does not
>> > match any function template declaration queue.d(10): Error: template
>> > std.stdio.File.writeln(S...) cannot deduce template function from
>> > argument types !()(string)
>> > 
>> > Remove the synchronized and it compiles fine with 2.055.
>> 
>> Technically, sychronized should go on the _class_ and not the function,
>> but I'm not sure if dmd is currently correctly implemented in that
>> respect (since if it is, it should actually be an error to stick
>> synchronized on a function). Regardless of that, however, unless you use
>> shared (I don't know if you are), each instance of queue is going to be
>> on its own thread. So, no mutexes will be necessary, but you won't be
>> able to have multiple threads writing to the same File. It could get
>> messy.
> 
> I get similar errors if I put synchronized on the class, or shared.  My
> best guess is that a File struct cannot currently (2.055) be shared or
> accessed in a synchronized context.
> 
> If I make the class synchronized and use __gshared on the File then it
> compiles.  I don't know if it works, though.

You could embed a File pointer in the synchronized queue, make sure it is 
the sole owner, and then cast to File* when using it. The concurrency 
chapter has a paragraph on this method that explains why it is not covered 
by the type system. 

I believe this is closest to your C++ example, I never did this though so 
I'm not 100% sure it works. 


Re: Multithreaded file IO?

2011-09-24 Thread Lutger Blijdestijn
If you didn't know, the concurrency chapter of tdpl is a free chapter: 
http://www.informit.com/articles/article.aspx?p=1609144

It has an example of file copying with message passing: 
http://www.informit.com/articles/article.aspx?p=1609144&seqNum=7


Re: Using pure to create immutable

2011-09-22 Thread Lutger Blijdestijn
Jesse Phillips wrote:

> The discussion on Reddit brought to my attention that pure functions can
> return and assign to an immutable.
> 
> 
http://www.reddit.com/r/programming/comments/knn5p/thoughts_on_immutability_in_d/c2lsgek
> 
> I am trying to modify the example request to make use of this, but have
> failed.
> 
> 
http://www.reddit.com/r/programming/comments/knn5p/thoughts_on_immutability_in_d/c2lrfpm
> 
> test.d(4): Error: cannot implicitly convert expression
> (makeFromArray([1,2,3])) of type test.List!(int).List to immutable(List)
> 
> Is this a bug? I can't identify where this issue would lie (works with
> inheritance and templating).
> 
> void main() {
>immutable a = makeFromArray([1,2,3]);
> }

For this to work, the arguments to makeFromArray have to be immutable:

void main() {
immutable(int)[] data = [1,2,3];
immutable a = makeFromArray(data);
}

> private abstract class List(T) {
>abstract bool isEmpty () const;
>abstract T head () const;
>abstract const(List!T) tail () const;
> 
> 
> }
> private final class Cons(T): List!T {
>immutable T head_;
>Cons!T tail_; // not immutable here for a reason
> 
>this(T h, Cons!T t) { head_ = h; tail_ = t; }
> 
>override bool isEmpty() const { return false; }
>override T head () const { return head_; }
>override const(Cons!T) tail () const { return tail_; }
> }
> 
> List!T makeFromArray(T)(T[] array) pure {

makeFromArray must take and return immutable types:

immutable(Cons!T) makeFromArray(T)(immutable(T[]) array) pure

>if (array.length == 0) { return null; }
> 
>auto result = new Cons!T(array[0], null);
>auto end = result;
> 
>for (int i = 1; i < array.length; ++i) {
>   end.tail_ = new Cons!T(array[i], null);
>   end = end.tail_;
>}
> 
>return result;
> }



Re: error when std.range.Cycle of static array is a member

2011-07-27 Thread Lutger Blijdestijn
Steven Schveighoffer wrote:

> On Mon, 25 Jul 2011 11:25:17 -0400, Steven Schveighoffer
>  wrote:
> 
> 
>> Please file a 'rejects-valid' bug.
> 
> http://d.puremagic.com/issues/show_bug.cgi?id=6385

Thanks, I'm sorry for slacking, have been a bit busy the last couple of 
days.



Re: error when std.range.Cycle of static array is a member

2011-07-24 Thread Lutger Blijdestijn
Jonathan M Davis wrote:

> On Sunday 24 July 2011 12:06:47 Lutger Blijdestijn wrote:
>> I'm trying to have a Cycle range of a static array as a struct member,
>> but getting a compilation error. Can anybody tell me if I'm doing
>> something wrong, or is this a bug?
>> 
>> import std.range;
>> 
>> struct Foo
>> {
>> ubyte[] buf;
>> Cycle!(typeof(buf)) cbuf1; // ok
>> 
>> ubyte[1024] staticBuf;
>> Cycle!(typeof(staticBuf)) cbuf2; // error
>> 
>> void test()
>> {
>> Cycle!(typeof(staticBuf)) cbuf3;
>> cbuf3 = cycle(staticBuf); // ok
>> }
>> }
>> 
>> /std/range.d(228): Error: template instance
>> std.array.front!(ubyte[1024u]) incompatible arguments for template
>> instantiation
> 
> static arrays are not ranges. You can't pop the front off of them, so no
> range- based algorithm would work with a static range. Now, you _can_ get
> a dynamic range over a static range and _that_ is a valid range, so what
> you need to do is make the Cycle a Cycle!(ubyte[]) rather than
> Cycle!(ubyte[1024]), and you when you pass the static array to cycle, you
> need to slice it: cycle(staticBuf[]).
> 
> - Jonathan M Davis

That would work, but the docs explicitly mention that Cycle is specialized 
for static arrays (for performance reasons). This is how cycle is 
implemented:

Cycle!(R) cycle(R)(ref R input, size_t index = 0) if (isStaticArray!R)
{
return Cycle!(R)(input, index);
}


error when std.range.Cycle of static array is a member

2011-07-24 Thread Lutger Blijdestijn
I'm trying to have a Cycle range of a static array as a struct member, but 
getting a compilation error. Can anybody tell me if I'm doing something 
wrong, or is this a bug?

import std.range;

struct Foo
{
ubyte[] buf;
Cycle!(typeof(buf)) cbuf1; // ok

ubyte[1024] staticBuf;
Cycle!(typeof(staticBuf)) cbuf2; // error

void test()
{
Cycle!(typeof(staticBuf)) cbuf3;
cbuf3 = cycle(staticBuf); // ok
}
}

/std/range.d(228): Error: template instance std.array.front!(ubyte[1024u]) 
incompatible arguments for template instantiation


Re: web development in D

2011-05-22 Thread Lutger Blijdestijn
joe wrote:

> I currently do most of my web development in PHP, with some work in Ruby
> with RoR. Right now I'm starting to think about building my own stack for
> web dev (I already use my own MVC framework and libs in PHP), but I'd
> really like to move to something faster and more powerful. Java or ASP.NET
> are two obvious choices, but I'm currently researching other alternatives
> (like D).
> 
> So first I was wondering if there has been any web development using D,
> and if there are many (or any) libraries/frameworks/other resources
> already available for this?

As mentioned Adam D. Ruppe has nice libs for web development, he managed to 
make a living out of it too so he must be doing something right :)

There is one other web framework for D2 called serenity, I'm not sure how 
far it is but you can check it out here:

https://github.com/mrmonday/serenity

Perhaps this is unnecessary to mention, but would you choose ASP.NET, I'd 
recommend against webforms and look into ASP.NET mvc. If haven't used the 
latter myself but I didn't like webforms too much and heard good things 
about the mvc framework. 

Good luck!



Re: Cannot interpret struct at compile time

2011-05-08 Thread Lutger Blijdestijn
Robert Clipsham wrote:

> Hey all,
> 
> I was wondering if anyone could enlighten me as to why the following
> code does not compile (dmd2, latest release or the beta):
> 
> struct Foo
> {
>  int a;
> }
> 
> string test()
> {
>  string str = "struct " ~ Foo.stringof ~ "_{";
>  foreach (j, f; Foo.tupleof)
>  {
>  enum fullFieldName = Foo.tupleof[j].stringof;
>  str ~= typeof(f).stringof ~ ' ' ~
> fullFieldName[Foo.stringof.length + 3 .. $];
>  }
>  return str ~ "}";
> }
> 
> void main()
> {
>  mixin(test());
> }
> 
> If fails with the errors:
> test.d(9): Error: Cannot interpret Foo at compile time
> test.d(19): Error: cannot evaluate test() at compile time
> test.d(19): Error: argument to mixin must be a string, not (test())
> test.d(19): Error: cannot evaluate test() at compile time
> test.d(19): Error: argument to mixin must be a string, not (test())
> 
> Thanks,
> 

test also doesn't compile normally on my box, dmd errors on Foo.tupleof. Not 
sure if this is illegal or not. I think you want the allMembers trait or 
something similar. Something like this:

import std.traits;

string test(T)()
{
string str = "struct " ~ T.stringof ~ "_{";
alias FieldTypeTuple!T FieldTypes;
foreach (i, fieldName; __traits(allMembers, T ) )
{
str ~= FieldTypes[i].stringof ~ " " ~ fieldName ~ ";";
}
return str ~ "}";
}

This works for your example but is a bit crude, I'm sorry for that, you'll 
have to modify it. ( allMembers also returns functions, including ctors 
while FieldTypeTuple doesn't. I also haven't read anything about the order 
in which FieldTypeTuple and allMembers return their elements )


Re: Linux: How to statically link against system libs?

2011-05-03 Thread Lutger Blijdestijn
Alexander wrote:

> On 29.04.2011 11:41, Spacen Jasset wrote:
> 
>> You still *cannot* link statically to kernel32.dll. That's the
>> difference. Linux glibc contains the C library functions *and* the
>> syscalls, which is the bit that causes the problems.
> 
>   But at least I know, that no matter where I am, as long as I am using
>   kernel32 only (no more dependencies), it will work on *any* Windows
>   system (obviously, keeping backward compatibility in mind - something
>   compiled on WinXP will work on all later
> versions) - which is not he case of Linux/glibc, unfortunately.
> 
>> msvcrt.dll and msvcrt.lib don't have any syscalls in them. they call
>> though kernel32.dll dynamically.
> 
>   Actually, they do. Calling kernel32 is like making a syscall, that's the
>   base of Win32 API, which is equivalent of Linux syscall.

A syscall is generally understood to be a call into the kernel for doing 
something that can't be done with user level privileges. So a call is either 
a syscall or it isn't, and none of kernel32 are. There are even functions in 
kernel32 which do not make a syscall.




Re: traits and class protection

2011-05-03 Thread Lutger Blijdestijn
Adam D.  Ruppe wrote:

> Is there a way in today's D to exclude members marked private and
> protected from processing in the __traits(allMembers) family of
> functions?
> 
> I thought if I at least put it in a separate module, trying to get
> a private member would fail to compile, but I tried it and it seems
> to work anyway... my private members are both showing up and being
> called from another module.
> 
> I'm open to filthy hacks too. Worst case is I can use a naming convention
> but I'd really like the public keyword to be the thing that actually
> matters.

Maybe some variation on the pimple idiom with opDispatch could work? It may 
be more trouble than its worth though. 

Most reflection mechanisms allow you to look at private symbols. This is 
probably not helpful to you, but whatever code that uses allMembers should 
just not do that and filter out private/protected members.




Re: Sample source code for D

2011-03-27 Thread Lutger Blijdestijn
Ishan Thilina wrote:

> I am a novice to D. Is there any place that I can get sample source codes
> for D ?
> 
> Thanks...!

examples from TDPL: http://erdani.com/tdpl/code/

You could browse github and dsource. Some blogposts also contain examples, 
see http://planet.dsource.org/ 


Re: using a binary tree container

2011-02-22 Thread Lutger Blijdestijn
Sorry I almost forgot: http://d.puremagic.com/issues/show_bug.cgi?id=5640

The issue with remove is talked about in digitalmars.D and perhaps not 
really specific to RedBlackTree.


Re: Can I parametrize template mixin's identifiers?

2011-02-19 Thread Lutger Blijdestijn
Nick wrote:

> I know I can parametrize template mixin types, but how about mixin
> identifiers? This is the code:
> 
> 
> 
> mixin template Box(T) {
>T val;
> }
> 
> class Set(A, B) {
>mixin Box!A a;
>mixin Box!B b;
> }
> 
> alias Set!(int, int) IntSet;
> 
> int main(string[] argv) {
>scope auto s = new IntSet();
>s.a.val = 3;
> }
> 
> 
> 
> As you can see, the A and B types can be changed and with them the boxed
> values. But they need disambiguation, since they have identically named
> members. I know only to hard-code that disambiguation.
> 
> I need this because I intend to change (A, B) with a type list
> eventually and I need to make operations on the boxed types independent
> on the template mixin  identifiers (a, b).
> 
> This pattern comes from C++ code, where Box(T) would be classes, Set (A,
> B, ...) would recursively apply multiple inheritance on the type list.
> Then each Box members could be addressed by casting to the correct Box(T).
> 
> Any idea if this is possible in D?
> 
> Thanks!

Possible yes, but probably not so pretty. There must be some places in 
phobos where something like this is done (better), perhaps in the code for 
tuples in std.typecons. Here is my unpolished attempt:

mixin template Box(T)
{
T val;
}

mixin template MixinFields(P...)
{
/* P[0] is the template to use as mixin
 * P[1] is the type to be use as parameter for P[0]
 * P[2] is the symbol name the mixin will be aliased to
 */
mixin("mixin " ~ __traits(identifier, P[0]) ~ "!(" ~ P[1].stringof ~ ")
  " ~ P[2] ~ ";");
static if(P.length > 3)
mixin MixinFields!(P[0], P[3..$]);
}


class Set(T...)
{
mixin MixinFields!(Box, T);
}

alias Set!(int, "a", int, "b") IntSet;

void main()
{
scope auto s = new IntSet();
s.a.val = 3;
} 


Re: Double-dispatch

2011-02-13 Thread Lutger Blijdestijn
Sean Eskapp wrote:

> I remember in C++, I had to do double-dispatch using the visitor pattern.
> This is cumbersome, just because each subclass has to have the exact same
> singly-dispatched code that looks like:
> 
> void dispatch(Base& other)
> {
>other.dispatch(*this);
> }
> 
> Is there a nicer way to do this in D, or am I stuck with the same thing?

There isn't really, but you can take out some of the boilerplate with a 
mixin, which goes a long way:

// The template parameter Visitor is not actually needed, depending on 
// what you want to do
mixin template Accept(Visitor)
{
void accept(Visitor v)
{
v.visit(this);
}
}

class Stuff
{
mixin Accept!IStuffVisitor;
}



With some ctfe it's also not too hard to take out the boilerplate of 
creating the visitor interface with a bit of code generation, though I'm not 
sure if it's worth it.


Re: using a binary tree container

2011-02-13 Thread Lutger Blijdestijn
Dominic Jones wrote:

> Hello,
> 
> I have a list of strings and I want to determine whether or not a
> particular string in the is in that list. Assuming I should store the list
> of strings in a binary tree to facilitate fast searching, I had a look at
> the std.container documentation and found RedBlackTree, but the
> documentation for it has no examples. May someone offer an example of how
> to use it?
> 
> Thank you,
> Dominic Jones

I tried it out and it's simple to use but I stumbled upon some issues. (See 
below) As others have commented, regular AA's will work fine for this 
purpose too. Probably the best reason why you would choose a RedBlackTree 
over AA is when you also need them sorted, this you get for free. A tree is 
also likely to  consume less memory, which may or may not matter.  

Example:

import std.stdio;
import std.container;

void main()
{
auto stuff = ["foo", "bar"];

/* using make instead of the constructor ensures the code will work 
   when RedBlackTree will become a class: */

auto set = make!(RedBlackTree!string)(stuff);

/* iterates in order: */
foreach( value; set )
writeln(value);

set.stableInsert("baz");

/* the 'in' operator returns bool, not a pointer to the element like
   builtin aa's do: */
assert( "baz" in set );
}

Now for the issues, this doesn't work but it should:

auto set = make!(RedBlackTree!string)("foo", "bar");

Error: template std.container.RedBlackTree!(string).RedBlackTree.__ctor(U) 
if (isImplicitlyConvertible!(U,Elem)) does not match any function template 
declaration
Error: template std.container.RedBlackTree!(string).RedBlackTree.__ctor(U) 
if (isImplicitlyConvertible!(U,Elem)) cannot deduce template function from 
argument types !()(string,string)
...


I couldn't see any function to remove a single element from the tree and  
std.algorithm.remove doesn't work. Removing a range also doesn't work for 
strings:

set.remove(stuff);

Error: function std.container.RedBlackTree!(string).RedBlackTree.remove 
(Range r) is not callable using argument types (string[])
Error: cannot implicitly convert expression (stuff) of type string[] to 
Range

I'll file these issues soon, when I have the time.


Re: Generic method that takes in either delegate or function

2011-01-12 Thread Lutger Blijdestijn
%u wrote:

> Hi,
> 
> Is there any way to specify a parameter as "something that can be called
> with parameter types A, B, C and that returns a value of type D", without
> caring whether it's a delegate, a function, or an object that overloads
> opCall? (This might require the use of templates, but I still can't figure
> it out...)
> 
> Thank you!

Yes, look at std.traits. isCallable determines if a type can be called, 
ReturnType gives you the return type and ParameterTypeTuple obtaines a tuple 
of the parameters. In this example I used all three, isCallable is implied 
by the latter two so that is actually redundant:

import std.traits;
import std.stdio;
import std.typetuple;

int square(int a)
{
return a*a;
}

struct Squarer
{
int opCall(int a)
{
return a * a;
}
}

void foo(T)(T fun, int num)
if (isCallable!(T)
&& is(ReturnType!fun == int)
&& is(ParameterTypeTuple!(T) == TypeTuple!(int)))
{
writeln("square of ", num, ":", fun(num));
}

void main()
{
foo(&square, 2);
Squarer functor;
foo(functor, 2);
foo((int a) { return a * a; }, 2);
}

Another (efficient) way to do this is with alias template parameters, this 
determines not the type of the object / function / delegate, but the actual 
symbol directly. However, it must be able to access that symbol, see this 
example:

void foo2(alias fun)(int num)
if (isCallable!(fun)
&& is(ReturnType!(fun) == int)
&& is(ParameterTypeTuple!(fun) == TypeTuple!(int)))
{
writeln("square of ", num, ":", fun(num));
}

void main()
{
Squarer functor;
foo2!square(2);
//foo2!functor(2); error: cannot access frame of function D main
foo2!((int a) { return a * a; })(2);
}

foo2 is trying to call opCall of the functor object, but it is a local 
variable of the main function so it cannot be called this way.


Re: discrimination of constructors with same number of parameters

2010-12-30 Thread Lutger Blijdestijn
spir wrote:

(...)
> 
> I like very much the template mixin solution. Would there be any
> difference in inheriting an interface (or even a plain type)? Also, can
> one presently rewrite this in D without _string_ mixin inside the
> template? (Else this solution is simply not acceptable for me: I'm
> allergic to code in strings; but don't ask me why ;-)
> 
> Denis
> -- -- -- -- -- -- --
> vit esse estrany ☣
> 
> spir.wikidot.com

Compared to inheriting interfaces: 
- works with primitive and struct types
- no dynamic polymorphism
- no performance penalty, likely less code size

You can do it without string mixins by explicitly writing the code the mixin 
automates. This should also work more or less, but I find it less clear:

struct NewType(T, string typename)
{
alias T this;
T base;
@disable void opAssign(T) {}
}

The typename parameter is arbitrary here, just to create a seperate type for 
each possible value. It might as well be an integer. 

alias NewType!(int, "Position") Position;
void func(Position position) { ... }

or used directly:

void func(Newtype!(int, "Position") position) { ... }



Re: discrimination of constructors with same number of parameters

2010-12-30 Thread Lutger Blijdestijn
Guilherme Vieira wrote:

> On Thu, Dec 30, 2010 at 12:18 PM, spir  wrote:
> 
>> On Thu, 30 Dec 2010 08:15:51 -0500
>> bearophile  wrote:
>>
>> > > But some language types (or machine types) can have very diverse
>> _human_ semantics, and thus be used for various purposes which should,
>> but cannot, be considered different:
>> >
>> > You may wrap your data in a struct.
>>
>> Yes, thank you for this hint. A kind of proxy struct? It can indeed be
>> used everywhere performance is not critical. But a side issue is that it
>> requires the 'alias this' hack, I guess, or forwarding every operation to
>> the actual, but wrapped, element. What do you think
>>
>> Denis
>> -- -- -- -- -- -- --
>> vit esse estrany ☣
>>
>> spir.wikidot.com
>>
>>
> Why is performance harmed by the use of a struct? Wouldn't it be
> zero-overhead like C++'s std::auto_ptr?
> 
> Also, the alias this and the forward might be a real good solution. And a
> mixin like Luger's might be jackpot, really. I just dislike the use in:
> 
> func2(Position(1)); // implicit conversion to int with alias this

This is deliberate, in this case I think of Position as a subtype of int so 
it is entirely reasonable to implicitly convert it. With opDispatch and 
operator overloading you could achieve the semantics you are after though.
  
> I guess that can be actually a bug, not a feature :) Maybe one day the
> function signature changes slightly and the problem is further disguised
> because "you're obviously passing the right Position here"... when it's
> actually an "int count" thing. The "alias this" thing is a good shorthand
> when assigning, though:
> 
> int a = pos; // implicit conversion from Position to int instead of
> int b = pos.base;
> 


Re: discrimination of constructors with same number of parameters

2010-12-30 Thread Lutger Blijdestijn
sybrandy wrote:

> Why not have something like this:
> 
> this (int[] data, string text, bool isMessage = false) {...}
> 
> Then, if you just pass in two parameters you treat it as a filename and
> if you pass in a "true" for the third parameter, it's a message.  It's
> not quite what you're looking for, but it's simple and pretty clean.
> 
> Casey

If you opt for this solution, an enum is slightly more verbose but much 
clearer:

enum IsMessage
{
Yes,
No
}

this (int[] data, string text, IsMessage isMessage = IsMessage.No) {...}


auto s = new S(data, text, IsMessage.Yes);

vs

auto s = new S(data, text, true);


I would still prefer a factory method or a struct wrapper though. 


Re: discrimination of constructors with same number of parameters

2010-12-30 Thread Lutger Blijdestijn
Guilherme Vieira wrote:

> On Thu, Dec 30, 2010 at 9:24 AM, bearophile
> wrote:
> 
>> Jonathan M Davis:
>>
>> > typedef is definitely on the way out, so that's not a solution,
>>
>> typedef is deprecated (because its semantics is not flexible enough and
>> because it doesn't play well with object oriented language features), but
>> I have a real need for something like it. Andrei has discussed about a
>> Phobos-based typedef replacement (based on structs + alias this), but
>> nothing concrete has come out yet. I hope to see something to solve
>> problems like spir ones.
>>
>>
>> > and it would be a pretty fragile one IMHO anyway.
>>
>> Please, explain better.
>>
>> Bye,
>> bearophile
>>
> 
> As far as I know, typedef was a form of "discriminated alias". I don't
> know the reasons for its deprecation. It just occurred to me that D's
> typedefs + templates could be quite handy in this case.
> 
> Consider:
> 
> struct semantic_wrapper(T)
> {
> this(T value) { this.value = value; }
> 
> T value;
> }
> 
> typedef semantic_wrapper!(int) Position;
> typedef semantic_wrapper!(size_t) Count;
> typedef semantic_wrapper!(string) Filename;
> typedef semantic_wrapper!(string) DirPath;
> 
> void func(Position pos) { ... }
> void func(Count c) { ... }
> void func(Filename fname) { ... }
> void func(DirPath dir) { ... }
> 
> void main()
> {
> func(Position(1)); // calls first overload
> func(Count(5)); // calls second
> func(Filename("file.txt")); // third
> func(DirPath("/dev/null")); // fourth
> 
> func(1); // fails
> func("blah"); // fails
> }
> 
> 
> Requires a little more typing, but sometimes it can be better than
> creating a new function name (which can get extra-big, non-telling or
> both) or than creating factory methods (which I personally dislike,
> although it's just a matter of taste most of the time; sometimes you may
> want to instantiate from inside a template and classes needing factories
> would not work, for example, but one could argue on the validity of this
> anytime).
> 
> Just giving my 2 cents. Dunno if I missed some detail.
> 

Here is an attempt to implement it, still needs support for writeln and 
lacks some details:

import std.stdio;

mixin template Newtype(T, string typename)
{
mixin("struct " ~ typename ~ " { alias base this; " ~ T.stringof ~
  " base;  @disable void opAssign(" ~ T.stringof ~ ") {} }");
}

mixin Newtype!(int, "Position");
mixin Newtype!(size_t, "Count");
mixin Newtype!(string, "FileName");
mixin Newtype!(string, "DirPath");

void func(Position pos) { writeln("position: ", pos.base ); }
void func(Count c) { writeln("count:", c.base); }
void func(FileName fname) { writeln("filename:", fname.base); }
void func(DirPath dir) { writeln("dirpath:", dir.base); }

void func2(int pos) { writeln("position: ", pos); }

void main()
{
  
func(Position(1)); // calls first overload
func2(Position(1)); // implicit conversion to int with alias this
func(Count(5)); // calls second
func(FileName("file.txt")); // third
func(DirPath("/dev/null")); // fourth
func(1); // fails
func("blah"); // fails

auto p = Position(1);
p = 2; // fails
p.base = 4; // ok, explicit
}


Re: inlining

2010-12-07 Thread Lutger Blijdestijn
Lutger Blijdestijn wrote:

> spir wrote:
> 
>> On Tue, 07 Dec 2010 13:44:18 +0100
>> Lutger Blijdestijn  wrote:
>> 
>>> There are some other conditions that prevent inlining, it's best to
>>> check for it. iirc also functions with loops, delegate and ref
>>> parameters cannot be inlined for example. I'm not so sure about ref,
>>> that may have been improved since the last time I checked. Perhaps also
>>> for some class of delegates, at least ldc supposedly can inline some
>>> functions with delegate parameters.
>> 
>> What do you mean with ref, ref parameters? If yes, why ar they
>> problematic?
>> 
>> Denis
>> -- -- -- -- -- -- --
>> vit esse estrany ☣
>> 
>> spir.wikidot.com
> 
> this:
> 
> void foo(ref int a) { a++; }
> 
> At the time I checked, this function could not be inlined by dmd, which
> can cost performance in some cases.

ok I checked it, it seems the dmd has improved in the meantime and is able 
to inline this case now. 

For reference:

void foo(ref int a ) { a++; }
void bar(int* a ) { a++; }

void main()
{
int a;
foo(a);
bar(&a);
}

compile with -profile -inline -O and run it, it will produce a trace.log and 
trace.def file. The trace.def contain the optimal order in which to link the  
functions, the trace.log file contains a call graph and a table of timings.
(you won't see anything interesting here, because everything is inlined). 
It's a great way to check for performance bottlenecks. 


Re: inlining

2010-12-07 Thread Lutger Blijdestijn
spir wrote:

> On Tue, 07 Dec 2010 13:44:18 +0100
> Lutger Blijdestijn  wrote:
> 
>> There are some other conditions that prevent inlining, it's best to check
>> for it. iirc also functions with loops, delegate and ref parameters
>> cannot be inlined for example. I'm not so sure about ref, that may have
>> been improved since the last time I checked. Perhaps also for some class
>> of delegates, at least ldc supposedly can inline some functions with
>> delegate parameters.
> 
> What do you mean with ref, ref parameters? If yes, why ar they
> problematic?
> 
> Denis
> -- -- -- -- -- -- --
> vit esse estrany ☣
> 
> spir.wikidot.com

this:

void foo(ref int a) { a++; }

At the time I checked, this function could not be inlined by dmd, which can 
cost performance in some cases.


Re: inlining

2010-12-07 Thread Lutger Blijdestijn
Jonathan M Davis wrote:

> On Tuesday 07 December 2010 03:05:28 spir wrote:
>> Hello,
>> 
>> Does dmd inline when appropriate (eg single-line func)? or is there a
>> hint keyword? or what else? Eg how to have this inlined:
>> 
>> private bool isPrecomposedHangulSylable (Code code) {
>> /** whether code is a precomposed Hangul syllable ;-) */
>> return (code >= FIRST_HANGUL_SYLLABLE) && (code <=
>> LAST_HANGUL_SYLLABLE); }
> 
> C++ has the inline keyword, and it is used only as a hint to the compiler.
> The compiler is free to follow it or ignore it as it sees fit, so its
> usefulness is debateable. D does _not_ have the inline keyword. It just
> leaves it up to the compiler entirely. Note that the -inline flag enables
> inlining.
> 
> IIRC, no functions which have lazy parameters or include inline assembly
> will ever be inlined. And, of course, if a function is long, the compiler
> is unlikely to choose to inline it (though maybe it would choose to if the
> function is only ever called once - that's up to the inliner).
...
> - Jonathan M Davis

There are some other conditions that prevent inlining, it's best to check 
for it. iirc also functions with loops, delegate and ref parameters cannot 
be inlined for example. I'm not so sure about ref, that may have been 
improved since the last time I checked. Perhaps also for some class of 
delegates, at least ldc supposedly can inline some functions with delegate 
parameters.



Re: Why is 'scope' so weak?

2010-11-23 Thread Lutger Blijdestijn
Lars T. Kyllingstad wrote:

> If I've understood things correctly, by marking a delegate parameter with
> 'scope' you tell the compiler not to create a true closure for the
> delegate.  Effectively you're saying "I promise not to escape this
> delegate, so you don't need to copy its context to the heap".
> 
> In brief, my question is:  Why doesn't the compiler enforce this
> promise?  In particular, why is 'scope' not a type constructor?
> 
> (Note that this is mostly a question out of curiosity, and not really a
> proposal for a new feature.  I imagine it has been discussed in the past
> and rejected for some reason.)
> 
> Considering that the compiler enforces proper use of pure, nothrow,
> const, and all those other things, it doesn't seem much harder to do the
> same with scope.
> 
> As an example, I really can't see a reason why obviously wrong code like
> this should be allowed:
> 
> void delegate() globalDg;
> 
> void foo(scope void delegate() dg)
> {
> globalDg = dg;
> }

Most likely it is not yet implemented? It's hard to find something on this 
topic, I couldn't find anything in the spec or tdpl. I did found this one 
post by Andrei about your question:

http://permalink.gmane.org/gmane.comp.lang.d.concurrency/617
 
> Here's a slightly less obvious example, which also compiles successfully:
> 
> void foo(void delegate() dg);  // Who knows what this does?
> 
> void bar(scope void delegate() dg)
> {
> foo(dg);
> }
> 
> -Lars





Re: publish a lib

2010-11-21 Thread Lutger Blijdestijn
spir wrote:

> Hello,
> 
> On which list is one supposed to publish about a lib (text processing
> toolkit) that may or not be useful to others, that may or not be
> interesting in stdlib? general D list, Phobos, announce,... ?
> 
> Denis
> -- -- -- -- -- -- --
> vit esse estrany ☣
> 
> spir.wikidot.com

D.announce, if for phobos perhaps just D or the phobos mailing list.


Re: struct vs class

2010-11-14 Thread Lutger Blijdestijn
spir wrote:

> On Sun, 14 Nov 2010 12:02:35 +
> div0  wrote:
> 
>> > Both of these points may conflict with semantic considerations above:
>>  > we may want to use structs for fast creation, but if ever they mean
>>  > "things", we must think at referencing them manually and/or using
>>  > ref parameters. We may want to use classes for light passing,
>>  > but if they mean values, we must either never assign them or
>>  > manually copy their content. It's playing with fire: very
>>  > dangerous risks of semantic breaks in both cases...
>> 
>> Perhaps, but they are tools to implement a program design;
>> it's the program design that should be driving your choices not abstract
>> semantic considerations. Go down that route and you'll never get
>> anything done.
> 
> I do not really get what you mean with "program design" as opposed to
> "semantic considerations". I tend to think that "program design" should
> precisely be driven by "semantic considerations" -- and that it's the main
> purpose of good language design to allow this as straightforwardly as
> possible. A bad langage is for me one in which one can hardly express what
> is meant -- leading to what I call "semantic distorsion" ;-). So, what is
> "program design" for you?
> 
> Denis
> -- -- -- -- -- -- --
> vit esse estrany ☣
> 
> spir.wikidot.com

If I may add my 2 cents: program design is where, in another response, you 
choose to pass a cursor into a source text by reference and have methods 
update that reference directly instead of returning a new cursor. You have 
chosen a class, but a pointer inside a struct it could be done as well.  




Re: exception types & objects

2010-10-20 Thread Lutger
spir wrote:

> On Tue, 19 Oct 2010 14:52:20 +0200
> "Simen kjaeraas"  wrote:
> 
>> > I was expecting (from exp with other language) there to be a root
>> > Error or Exception type implementating base exception mechanics and/or
>> > an imposed interface to comply with (esp a kind of string method
>> > returning what text to write out when the exception is not caught).
>> > How does this work, and how to use it concretely?
>> 
>> There is a base class Exception and Error, as well as the base interface
>> Throwable, which the aforementioned implement. Using this is more of a
>> convention than absolute necessity, but it is used all over Phobos and
>> druntime, and it is heavily discouraged not to use those as bases.
> 
> Good. Is this documented somewhere (have searched language and library
> references before asking: found some documents on peculiar aspects, but
> none describing the mechanism and how to use).

Unfortunately the relevant docs here seem to be a bit out of date.

look up nothrow:
http://www.digitalmars.com/d/2.0/function.html

this is out of date wrt the throwable hierarchy:
http://www.digitalmars.com/d/2.0/errors.html

contains related info, recommended:
http://www.digitalmars.com/d/2.0/exception-safe.html

If you want more details you could look up the header files of druntime 
distributed with the dmd package, specifically:

src/druntime/import/object.di: contains the Throwable, Error and Exception 
interfaces

src/druntime/import/core/exception.di: contains a few derived Exceptions


Re: Sorting after map

2010-10-20 Thread Lutger
clueless wrote:

> Hi. I want to have a sorted result of map-function, that is (in
> pseudocode):
> 
> sorted(map!(fun)(arr))
> 
> How can I do that? I have tried something like:
> 
> auto s = map!(fun)(arr);
> //sort(s);
> //sort(s[]);
> //sort(s.dup);
> writeln(s);
> 
> but without success.
> 
> Thanks in advance.

Hi, I'm not sure if it is supposed to work or not. sort is inplace but map   
does not offer opIndexAssign which sort needs. You can circumvent it by 
creating an array of the map:

import std.array;

auto s = array(map!fun(arr));
sort(s);


Re: C structs

2010-10-19 Thread Lutger
Mafi wrote:

> Hello,
> I'm trying to write some SDL wrapper. After a long fight against
> objconv, implib and optlink I finally got SDL loading. Hurray! Now I'm
> going to write a wrapper for SDL_Surface. I will only use surface
> poiters so my questions is if I can safely put these pointers into class
> instances which on destruction free the surface (iff it's no display)?

Some caveats apply:

iirc with SDL you typically initialize and close down the different 
subsystems. With the GC finalizing surfaces will be freed after sdl 
shutdown, dunno if that's legal.

Also, sdl surfaces may take lots of space, so if possible I would free them 
when no longer in use. The GC may not collect at all, or late. But this may 
or may not be a problem. 


Re: Any usable parsers for D2 around?

2010-10-15 Thread Lutger
Andrej Mitrovic wrote:

> Hey,
> 
> I've been looking for a D2 parser.. there seems to be a few D1 lexers,
> parsers, and even some minimal semantic analysis tools but I can't find
> much of anything for D2. Perhaps Goldie will be D2 compatible some day
> soon. :)
> 
> There's a "CodeAnalyzer" lexer/parser with some minimal semantics, but
> it's D1 only and kind of dead for some years. The Poseidon author added
> some D2 support for it in his editor, so I have kept an eye on that. But
> interfacing with D1 code from D2 is kind of complicated, and I need to
> use it from D2. (I guess I could get away with writing a DLL with a
> simple interface for D2 or something..).
> 
> I had a visit on the prowiki site and most of the parser projects there
> are either D1-only or dead. So is there anything usable for D2?
> Specifically I need these tools for use with an editor/IDE, which is
> something I'm working on for fun atm. But working on a parser is probably
> a ton of work, + the whole thing screams NIH to me. Luckily enough I
> don't have to reinvent a GUI and an editing control, there's DFL and
> Scintilla which are pretty awesome for my needs.
> 
> Maybe I should take a look at how Descent/DDT and VisualD do their
> parsing.. :)

You can try working with ddmd on dsource. It is a port from the dmd 
frontend, currently at 2.039. 


Re: toString(char*)?

2010-10-11 Thread Lutger
Lars T. Kyllingstad wrote:

> On Mon, 11 Oct 2010 21:46:26 +0200, Lutger wrote:
> 
>> Where can I find the function to convert from c-style string to a normal
>> D string? It used to be toString in std.string, but that one is
>> deprecated.
>> 
>> Thanks.
> 
> import std.conv;
> 
> const char* cString;
> string dString = to!string(cString)
> 
> -Lars

Oh wow, I didn't knew that would work. Awesome. 


toString(char*)?

2010-10-11 Thread Lutger
Where can I find the function to convert from c-style string to a normal D 
string? It used to be toString in std.string, but that one is deprecated.

Thanks.


Re: Destruction Sequence: module and classes defined within

2010-10-08 Thread Lutger
Lars T. Kyllingstad wrote:

> On Tue, 05 Oct 2010 23:25:36 +0200, vano wrote:
> 
>> The code below:
>>  module used;
>> 
>>  import std.stdio;
>> 
>>  class ClassA {
>>  this()  { writeln("A ctor"); }
>>  ~this() { writeln("A dtor"); }
>>  }
>> 
>>  static this()  { writeln("used.sctor"); } static ~this() {
>>  writeln("used.sdtor"); }
>> 
>>  void main() {
>>  auto a = new ClassA();
>>  }
>> produces the following output (DMD v2.049):
>>  used.sctor
>>  A ctor
>>  used.sdtor
>>  A dtor
>> 
>> The question is: should the module be allowed to be unloaded before all
>> module-level objects/structures are destructed/unloaded?
> 
> 
> I'm no expert on this, but I think it has to be that way.  Consider this:
> 
>   class Foo { ... }
>   Foo foo;
> 
>   static this()
>   {
>   foo = new Foo;
>   }
> 
>   static ~this()
>   {
>   foo.doStuff();
>   }
> 
> So you see, if foo had already been destroyed and garbage collected, my
> program would have crashed when the module static destructor was run.
> Thus, I guess, running the garbage collector for the final time has to be
> one of the last things done on program shutdown, after running all module
> destructors.
> 
> -Lars

In this case however, foo is still referenced whereas in the original example 
'a' is unreferenced after main exits.

I could only find this in the spec: "The garbage collector is not guaranteed to 
run the destructor for all unreferenced objects." *

>From reading the spec, I think that all one can conclude is that after main 
unreferenced objects may be finalized any time, or not at all.

* http://www.digitalmars.com/d/2.0/class.html#Destructor


Re: Creating immutable data and sharing it

2010-09-21 Thread Lutger
Steven Schveighoffer wrote:

> On Tue, 21 Sep 2010 05:17:10 -0400, Lutger 
> wrote:
> 
>> I'm still a bit fuzzy on how to create immutable data and when said data
>> is safe
>> to share across threads.
>>
>> To begin with, there is .idup, string literals and constructors of
>> immutable
>> objects. Those can be safely shared, no problem, right?
> 
> idup is not safe (along with dup), it is the equivalent of a cast right
> now.  You must still ensure the data has no aliases, or the data idup'd
> consists of all value types.
> 
> See this bug report: http://d.puremagic.com/issues/show_bug.cgi?id=3550

Good to know, I voted for it. There are quite a few bugs related to this topic, 
looks like I have some more studying to do.


Re: Creating immutable data and sharing it

2010-09-21 Thread Lutger
Simen kjaeraas wrote:

> Lutger  wrote:
> 
>> Aha, thanks. I have made a conceptual diagram to help understand this,
>> would you
>> care to take a look and confirm whether this is correct or not?
>>
>> 
http://picasaweb.google.com/Lutger.blijdestijn/Illustration#5519337139518828386
>>
>> I hope it explains itself, the edges reflect the types and the nodes the
>> memory
>> storage.
> 
> That looks very much correct. I'm somewhat confused by the 'static data'
> part, as it connected only to one thread, and static data is in TLS, as far
> as I know.

Good, things start falling into places. About the static part, I realized it 
too 
late, I meant the readonly data (like .rodata) part of the executable where 
string literals and such are dumped. The missing connection was for 
uncluttering.
 
>>> Immutable global state may be instantiated from non-immutable data in
>>> module constructors. I believe that is the canonical way.
>>>
>>
>> Sometimes this is not possible. For example if you want to create a data
>> structure from user input once, then use it read-only for the rest of the
>> program.
> 
> Indeed. In that case, would a shared pointer/array to immutable data work
> for
> you? In such a case, you are free to have local (non-shared) pointers to
> the
> very same data, and thus have no need for locking (which might be needed to
> dereference the shared pointer).

I would love to do something like that:

1. create a thread that makes a complex data structure from user input
2. said thread dies when it is finished, but gives a message back to the parent 
consisting of a pointer to the data that is now cast as immutable.

Now all mutable aliases are destroyed and the program can enjoy doing parellel 
work on the data safely, avoiding any locking. It looks like this is possible.


Re: Creating immutable data and sharing it

2010-09-21 Thread Lutger
Simen kjaeraas wrote:

> Lutger  wrote:
> 
>> char[] s = ...;
>> immutable(char)[] p = cast(immutable)s.dup; // ok, unique reference
>>
>> I do not understand how that works with sharing. Since immutable data is
>> implicitly shared but the data that p refers to is allocated on the TLS,
>> how can
>> you share this? I always thought that threads do not have access to each
>> others
>> TLS at all?
> 
> Only p itself is in TLS - the pointed-to data is on the heap.

Aha, thanks. I have made a conceptual diagram to help understand this, would 
you 
care to take a look and confirm whether this is correct or not?

http://picasaweb.google.com/Lutger.blijdestijn/Illustration#5519337139518828386

I hope it explains itself, the edges reflect the types and the nodes the memory 
storage. 
 
> 
>> Finally a practical question: when you have a data structure that is too
>> complex
>> to create in a constructor, want to create it and then make it
>> immutable, what
>> is the current way to go about this? If it is created by one thread,
>> would it be
>> ok to type it as __gshared, cast to immutable and then send a message to
>> other
>> threads? Is __gshared required in this case?
> 
> Immutable global state may be instantiated from non-immutable data in
> module constructors. I believe that is the canonical way.
> 

Sometimes this is not possible. For example if you want to create a data 
structure from user input once, then use it read-only for the rest of the 
program.


Creating immutable data and sharing it

2010-09-21 Thread Lutger
I'm still a bit fuzzy on how to create immutable data and when said data is 
safe 
to share across threads.

To begin with, there is .idup, string literals and constructors of immutable 
objects. Those can be safely shared, no problem, right?

But then, the spec mentions casting to immutable is ok if you do not have any 
mutable aliases left (http://www.digitalmars.com/d/2.0/const3.html):

char[] s = ...;
immutable(char)[] p = cast(immutable)s.dup; // ok, unique reference

I do not understand how that works with sharing. Since immutable data is 
implicitly shared but the data that p refers to is allocated on the TLS, how 
can 
you share this? I always thought that threads do not have access to each others 
TLS at all?

Finally a practical question: when you have a data structure that is too 
complex 
to create in a constructor, want to create it and then make it immutable, what 
is the current way to go about this? If it is created by one thread, would it 
be 
ok to type it as __gshared, cast to immutable and then send a message to other 
threads? Is __gshared required in this case? 



Re: Unit tests and verifying pre/post-conditions and invariants

2010-08-15 Thread Lutger
Jonathan M Davis wrote:

> Is there a standard and/or acceptable way to make sure that pre-conditions,
> post-conditions, or invariants _fail_ when running unit tests? That is, lets
> say I had a function like this
> 
> void func(int x)
> in
> {
> assert(x < 8);
> }
> body
> {
>   //...
> }
> 
> 
> and I wanted to test to make sure that func() couldn't be called with any int
> greater or equal to 8, what would I do? The best that I can think of is to
> catch an AssertError and ignore it. e.g.
> 
> unittest
> {
> try
> {
> func(8);
> assert(0);
> }
> catch(AssertionError ae)
> {}
> }
> 
> 
> But catching AssertionErrors is generally a bad idea. As I understand it, when
> anything derived from Error is thrown, code is not left in a proper state,
> with stuff like destructors being skipped. Would it be okay to catch it in a
> case like this, or is it a really bad idea? If it's a bad idea, I haven't a
> clue how to verify that pre-condition, post-conditions, and invariants are
> correct.
> 
> - Jonathan M Davis

Thats a good one. It used to be so that dmd would assume a halt and you could 
get segfaults for continuing on. I *believe* this has changed and it is ok to 
catch AssertError in this scenario. The only thing I can think of is that 
nothrow functions can be optimized by the compiler, but are not typechecked for 
throwing Error. 

Even if this is correct, you still have the problem foo could call other 
functions that assert, which invalidates at least two contract checks. This may 
 
require some care. Perhaps an idea is to define a PreconditionError and 
PostconditionError and wrap them in a function similar to enforce, so you can 
differentiate more easily where the error is coming from. This way you also get 
better error messages and have one point where to change the behavior if this 
may be required.


Re: [OT] Is this more readable, or just way too verbose?

2010-08-10 Thread Lutger
simendsjo wrote:

> Lutger wrote:
...
>  I didn't increase the if nesting though.

I count 2 nested if-statements inside of the foreach loop in the original, you 
have 3 nested if-statements.
 
> Something like this then?

Looks good to me, yes. 


Re: [OT] Is this more readable, or just way too verbose?

2010-08-09 Thread Lutger
simendsjo wrote:

> I took splitlines from std.string, which is a simple, short method.
> 
> S[] splitlines(S)(S s)
> {
>  size_t istart;
>  auto result = Appender!(S[])();
> 
>  foreach (i; 0 .. s.length)
>  {
>  immutable c = s[i];
>  if (c == '\r' || c == '\n')
>  {
>  result.put(s[istart .. i]);
>  istart = i + 1;
>  if (c == '\r' && i + 1 < s.length && s[i + 1] == '\n')
>  {
>  i++;
>  istart++;
>  }
>  }
>  }
>  if (istart != s.length)
>  {
>  result.put(s[istart .. $]);
>  }
> 
>  return result.data;
> }
> 
> 
> I guess it takes less than 30 seconds to fully understand this method.
> Then I rap.. I mean refactored it to this:
> 
> S[] mysplitlines(S)(S s)
> {
>  const CR = '\r';
>  const LF = '\n';
> 
>  size_t istart;
> 
>  auto result = Appender!(S[])();
> 
>  foreach (i; 0 .. s.length)
>  {
>  immutable c = s[i];
> 
>  immutable isCR = (c == CR);
>  immutable isLF = (c == LF);
> 
>  if (isCR || isLF)
>  {
>  auto line = s[istart .. i];
>  result.put(line);
> 
>  istart = i + 1;
> 
>  // Might be CRLF. In that case we need to consume LF too
>  if (isCR)
>  {
>  immutable hasMoreCharacters = (i + 1 < s.length);
>  immutable nextIsLF = hasMoreCharacters && (s[i + 1] == LF);
>  immutable isCRLF = isCR && nextIsLF;
> 
>  if (isCRLF)
>  {
>  i++;
>  istart++;
>  }
>  }
>  }
>  }
> 
>  immutable lineNotEmpty = (istart != s.length);
>  if (lineNotEmpty)
>  {
>  auto lastLine = s[istart .. $];
>  result.put(lastLine);
>  }
> 
>  return result.data;
> }
> 
> 
> Yes, I'm reading some books now and don't have much experience :)
> 
> It went from a small 26 line, very readable function to 48 lines (85%
> increase!) with many more temporary variables..
> 
> So... Do you think this kind of code is (more) readable, or just way too
> verbose and doing more harm than good?

The CR and LF constants are a bit too much, probably because they don't really 
abstract over the literals which I can actually parse faster. The isCR and isLF 
are nice however. Taking it a step further:

bool canSplit = inPattern(c,"\r\n");
if (canSplit)
{
  ...

You have increased the nesting of ifs to 3 inside a for-loop. Personally I 
don't 
read deep nesting very well. To go for readability I would use a small function 
for the entire expression: 

if( s[i..$].startsWithCRLF() ) // same as startsWithCRLF(s[i..$])
{
  i++;
  istart++;
}

or use std.algorithm: if ( s[i..$].startsWith("\r\n") )
 
> And will the compiler generate slower code, or should the optimizer be
> able to inline the temporaries?

I don't think it matters much, but you can only tell by testing. There is a 
benchmark function (called benchmark iirc) somewhere in phobos to start with 
and 
dmd has a builtin profiler too.


Re: Casting away const

2010-08-09 Thread Lutger
Steven Schveighoffer wrote:

> On Mon, 09 Aug 2010 14:39:58 -0400, Lutger 
> wrote:
> 
>> bearophile wrote:
>>
>>> Mafi:
>>>> I think, that isn't a good idea.
>>>
>>> I agree, that idea doesn't work well.
>>>
>>> Bye,
>>> bearophile
>>
>> I think it still is a good idea to forbid this in safe mode. Perhaps in
>> trusted
>> too.
> 
> Note, this isn't any less safe than defining whatever you want for a C
> function:
> 
> extern(C) int strlen(int x);
> 
> C has no mangling, so there is no storage of parameter types in the
> symbol.  You can call any C function with whatever parameters you want to
> define for them.  Making some set of parameters illegal because in some
> cases it might not be true where you don't prevent it in others because
> you can't prove it, is just simply useless.
> 
> -Steve

Well you manually add typing, I think that is useful. But come to think of it, 
extern(C) functions should not be allowed in @safe code at all, only via 
@trusted and then the typing is useful. Perhaps this has been talked about, but 
I'm not sure how far @trusted can be allowed to go.



Re: Casting away const

2010-08-09 Thread Lutger
bearophile wrote:

> Mafi:
>> I think, that isn't a good idea.
> 
> I agree, that idea doesn't work well.
> 
> Bye,
> bearophile

I think it still is a good idea to forbid this in safe mode. Perhaps in trusted 
too.


Re: d equivilent of java's public static class fields

2010-08-08 Thread Lutger
bearophile wrote:

> Simen kjaeraas:
>> class Answer {
>>  alias int Correctness;
>>  enum Correctness CORRECT = 0;
>>  enum Correctness WRONG = 1;
>> 
>>  Correctness _answerCode;
>>  string _answerText;
>> 
>>  @property Correctness answerCode( ) const {
>>  return _answerCode;
>>  }
> 
> 'Correctness' there begs to be a typedef :-]
> 
> Bye,
> bearophile

I think it wants to go boolean.




Re: std.variant and const

2010-08-07 Thread Lutger
Jonathan M Davis wrote:

> On Saturday 07 August 2010 05:42:53 Lutger wrote:
>> Variant in phobos doesn't work well with being const, toHash and opEquals
>> for example are not marked as const methods. I have tried to work around
>> it with careful casting, but it is too unsafe and just too complex for
>> something that is supposed to make life easier.
>> 
>> Does anybody know if this is a temporary problem with variant itself or
>> related to other bugs or limitations? Should I file a bug report for this?
>> I could only find this: http://d.puremagic.com/issues/show_bug.cgi?id=3795
> 
> The fact that Object is not const-correct is a huge problem.
> http://d.puremagic.com/issues/show_bug.cgi?id=1824 covers that, but I don't
> know when it's going to be fixed.
> http://d.puremagic.com/issues/show_bug.cgi?id=3748 which deals with inout
> probably has to be fixed first.
> 
> So, I don't know whether there's really an issue with Variant itself, but the
> fact that functions like toHash() opEquals() aren't const is a big problem
> which is supposed to be addressed at some point but hasn't yet.
> 
> - Jonathan M Davis

Ouch. Thanks for the intel. 


std.variant and const

2010-08-07 Thread Lutger
Variant in phobos doesn't work well with being const, toHash and opEquals for 
example are not marked as const methods. I have tried to work around it with 
careful casting, but it is too unsafe and just too complex for something that 
is 
supposed to make life easier. 

Does anybody know if this is a temporary problem with variant itself or related 
to other bugs or limitations? Should I file a bug report for this? I could only 
find this: http://d.puremagic.com/issues/show_bug.cgi?id=3795


Re: Sections in Ddoc?

2010-08-02 Thread Lutger
Philippe Sigaud wrote:

> Hi,
> 
> as per Nick's advice, I was reading on Goldie's GenDocs template documentation
> system:
> 
> http://www.semitwist.com/goldiedocs/v0.3/Docs/Tools/GenDocs/TemplateFormat/
> 
> That's a nice work, and I saw there something I'd like to do with Ddocs:
> sections. As in, document sections.
> 
> Ideally there are some modules I'd like to document that way:
> 
> 
> Module Name
> 
> some general documentation on the module, what its use is supposed to be, the
> things to do, etc. Imagine an algorithm module, for example.
> 
> Section #1 - Sorting.
> general documentation on the section, a specific part of the module. Say,
> sorting.
> 
> functions documentation for section 1.
> 
> Section #2 - Finding.
> another subject there, say finding elements in a range... General explanations
> on the modules assumptions, trade-off, etc.
> 
> functions documentation for section 2.
> 
> an so on...
> 
> But I cannot do that with DDocs. Or can I?
> Does anyone know a way to do this?
> 
> (ideally, I'd also like a summary-like part, like in Wikipedia :) )
> 
> Philippe

It isn't supported out of the box. You could further process ddoc output, I had 
something working nicely by spitting out xml instead of html and then using 
xquery to generate the docs, but am too much pressed for time to finish it. 

A more lightweight approach is to insert a css class though a custom ddoc macro:

API_GROUP = 

>From there you can use css selectors for styling. I'm not sure how far you can 
get with just css. A wee bit of jquery might help. It will be pretty awkard 
anyway I suppose.


Re: alias = compile-time variants?

2010-07-31 Thread Lutger
Jason Spencer wrote:

> == Quote from Philippe Sigaud (philippe.sig...@gmail.com)'s article
>> --0016e6d58a039d35e2048c9aa7e2
>>
>> I thought they could only be symbols. That is, an alias is a 'link',
> a sort
>> of pointer to a symbol: a template name, a module name, a function
>> name, etc.
> 
> Whatever confidence you inspired by removing type from the list is
> quickly lost and more when you add module name--I hadn't thought of
> that! :)
> 
> 
>> Wisdom, I don't know, as I still feel like I'm exploring things. But
>> template constraints are there to limit what you can instantiate.
>> ...
>> Say I have a template that takes an alias, fun, and a type, T.
>> fun is supposed to be a function, but in fact why limit it to that?
>> What I need is for foo to be callable with a T. So let's test for
>> that:
>> auto doSomething(alias fun, T)(T t)
>> if (is(typeof( fun(T.init) )))
>> {
>> // now that I'm here, I can freely use fun as a callable on any T
>>  auto result = fun(t);
>> // ...
>> }
> 
> I understand this example, and (most of) the mechanics of constraints.
> What I'm not so sure about is the recommended practice around their
> use.  I see lot's of code that doesn't check those things.  Suppose
> you left off the constraint and did:
> 
> class Foo(U){}
> doSomething!(Foo, int)(3)
> 
> it seems like there's a good chance you could get:
> 
> auto result = Foo!(int);  // type inferred from 3
> 
> (since this doesn't actually work like I'm saying, please conveniently
> imagine a similar case that does. :)

Sure, but that would be quite a gotcha since you went from calling something to 
merely instantiating a template. Perhaps there are such gotcha's, I am not 
aware 
of them. 
 
> Even with your constraint, I'm not sure I feel any more comfortable.
> If it compiles in the body of doSomething, it will compile in the
> constraint--not sure I've added any value.

Perhaps not in this case, but:
- constraints add documentation, such as isInputRange!T or IsCallable!fun
- you can add a constraint that may not be statically checked inside the body 
of 
the template. This way you can still reject template parameters considered to 
be 
invalid even if the template body *could* be instantiated with them.
- a constraint is a nice place to add better compiler error messages
 
> So how do you sleep at night not knowing if there's some funky syntax
> on somebody's template-that-takes-a-template which, when combined with
> some inference, might look like your function call on a value param?
> My initial reaction is to specify the hell out of the constraints, but
> I couldn't beat the feeling I was going overboard.  I suspect that
> most people rely on the fact that most improper calls won't compile.
> Maybe I'm still too new to the syntax to have a good feel for what
> will get caught, and what could interpreted by the compiler in
> multiple ways depending on the actual arguments.
> 
> So, do folks write constraints to ensure that modules don't get passed
> to their templates?  :)
> 
> Jason

Why not? As long as your module does the right thing, it may be used to 
instantiate my template :)


Re: Why assert is in the language?

2010-06-23 Thread Lutger
Ellery Newcomer wrote:

> On 06/22/2010 05:36 PM, Ali Çehreli wrote:
>> Jonathan M Davis wrote:
>>  > Steven Schveighoffer wrote:
>>
>>  >> all calls to assert are removed by the compiler in release mode. I
>> don't
>>  >> think there's a way to implement that via a library (it would be nice
>>  >> though!)
>>
>>  > Also IIRC, the compiler uses assert(0) to ensure that functions blow
>> up at
>>  > runtime if you manage to hit the end of them without a return statement.
>>
>> I just read in TDPL that the assert(0) calls in user code are not
>> removed even in release mode.
>>
>> Ali
> 
> Really?
> 
> // test.d
> void main(){
>   assert(0);
> }
> 
> $ dmd test -release
> $ ./test
> Segmentation fault (core dumped)
> 
> good job, dmd. Can anyone see if anything is going on here?

According to TDPL, assert(false) is treated specially and never removed. It 
serves two purposes:
- portable way of issuing the HLT instruction 
- telling the compiles that everything after is dead code, the compiler  
recognizes the meaning assert(false)


Re: How to chain constructor args to a template memeber

2010-03-11 Thread Lutger
BCS wrote:

> Using D2, I have a template class that looks something like this:
> 
> class C(T) { T t; }
> 
> (For simplicity, assume T is required to be a struct of some kind.) I want
> to have a constructor that passes on some of it's args to a constructor for
> t. This is easy as long as I don't need it to work for arbitrary
> constructors.
> 
> What I want to do (that doesn't seem to work) is this:
> 
> this(Args...)(int foo, float bar, Args args)
> {
>t = T(args);
> 
>...
> }
> 
> Any ideas on fixes or work arounds?
> 

Workaround if T has a single constructor, perhaps it can be generalized with 
some work:

this(int foo, float bar, std.traits.ParameterTypeTuple!(T.__ctor) args)
{
t = T(args);
}


Re: optional feature with contract inheritance? (design question)

2010-02-27 Thread Lutger
Jonathan M Davis wrote:

> Lutger wrote:
> 
>> 
>> True, it only adds AssertError and that could be replaced with regular
>> asserts.
>> 
>> Thanks.
> 
> ??? Regular asserts? When asserts in D fail, they throw an exception of
> type AssertError. So, unless you're talking about explicitly throwing an
> AssertError yourself (which seems rather silly to me), I don't know what
> you could mean by the difference of having an AssertError get thrown from
> having a "regular" assert.
> 
> - Jonathan M Davis

I wasn't clear, this is what I meant with 'regular' asserts:

void foo()
{
assert(precondition);
}

instead of:

void foo()
in
{
assert(precondition);
}
body
{ 
}





Re: optional feature with contract inheritance? (design question)

2010-02-27 Thread Lutger
Jonathan M Davis wrote:
...
> 
> Generally, I speaking, I think that having functions which override
> functions from a base class and throw if they're used is a bad design. It
> may be that it makes perfect sense in some contexts, but generally, I'd
> consider it a very bad idea. Personally, I hate it when APIs do that.

I agree, but it's sometimes hard to avoid. For example if you want a 
composite and component class to have a common interface, some operations 
won't make sense for components. The alternative to throwing is a no-op or 
return a null object. Or asserting.  
 
> Regardless of whether you consider that a good or bad idea though, there's
> no point in adding contracts into it. They don't add anything. If the
> feature is supported by the class, then no exception gets thrown. If it
> isn't, then an exception gets thrown. All adding asserts in preconditions
> does is make it an AssertError instead of whatever kind of exception you're
> throwing in the body. It doesn't add anything.
> 
> - Jonathan M Davis

True, it only adds AssertError and that could be replaced with regular 
asserts.

Thanks.













optional feature with contract inheritance? (design question)

2010-02-27 Thread Lutger
What do you think of the following use of contracts?

class Base
{
void useFeatureA()
in { assert(false, "Base does not implement feature A"); }
body
{ 
/* throw here? */ 
}

bool hasFeatureA()
{
return false;
}
}

class Derived : Base
{
override void useFeatureA()
in { assert(true); }
body 
{ 
/* do feature A */ 
}

override bool hasFeatureA()
{
return true;
}
}

In .NET this is supposedly called the optional feature pattern, recommended 
to use if you want to prevent factoring into too many interfaces. In .NET 
A.useFeatureA would just throw of course. 

Adding preconditions to functions in a derived class loosens the contract, or 
adds to the set of acceptable inputs so to speak. In this case, the 
polymorphic type of the object is considered as the (sole) input. 

Does it make sense? Is this a good/bad/ugly way of using contracts?


Re: Running external program from a D program [D2]

2010-02-23 Thread Lutger
"Jérôme M. Berger" wrote:

> Jonathan M Davis wrote:
>> Jesse Phillips wrote:
>>> As you may have noticed by the comments to on bug 3158. exec()[1] calls
>>> replace your process, this means it will not continue your program. To
>>> get arround this you find that people will first fork()[2] and exec on
>>> the child process.
>> 
>> Ah yes. Threads are all part of the same process, so you have to fork
>> rather than create a new thread. Whoops. I should have thought of that.
>> But I guess that comes from my almost never using fork and even only
>> using threads when I have to. Of course, it would be nice if there were a
>> function in phobos to abstract that out, but there's enough work to do on
>> phobos that that's probably not at the top of the list by any means.
>> 
>>> In order to get your standard output you would use the dup2()[3] call.
>>>
>>> Please note that I do not know how any of this will related to practices
>>> on Windows. And sadly this is not D specific and actually C stuff.
>>>
>>> 1. http://www.opengroup.org/onlinepubs/007908799/xsh/exec.html
>>> 2. http://www.yolinux.com/TUTORIALS/ForkExecProcesses.html
>>> 3. http://www.mkssoftware.com/docs/man3/dup2.3.asp
>> 
>> Well, it's good info. So, thanks. But it would be nice if that too were
>> nicely abstracted in phobos. The undocumented shell() command works, but
>> it uses the shell, so you have to worry about escaping characters. Bleh.
>> In any case, thanks for the info.
>> 
> In C, you have popen which allows to start a child process and
> capture either the standard input or the standard output. It is
> originally a POSIX function, but AFAIK it exists also on Windows
> (although it might be called _popen there).
> 
> Jerome

While convenient, popen also invokes the shell to do it's bidding so you 
will get shell expansion and some performance penalty.


Re: DMD on x86_64

2010-02-17 Thread Lutger
If you manage to find the proper 32 bit libraries, there is a configuration 
file for ld where you can specify the search paths, should be: 
/etc/ld.so.conf

The 64-bit distro's I have used fail to add the 32-bit lib paths to this 
file, even if you install the right packages.




assert fails to display file on dmd 2.040?

2010-02-02 Thread Lutger
Does anybody get this with 2.040? I couldn't find a bug report about it, 
so maybe it is due to my setup.


// in file test.d:
assert(false);

output: core.exception.asserter...@l(5): Assertion failure
   ^ not the right file

// in file test.d:
assert(false, "ok");

output: core.exception.asserter...@test.d(5): ok




Re: Why it doesn't compile in D 2.0?

2010-01-17 Thread Lutger

On 01/17/2010 01:38 AM, Simen kjaeraas wrote:

Lutger  wrote:


Perhaps this is or should be a bug. You can override dup to work in ctfe:

char[] dup(string str)
{
return str.dup;
}

class Test {
string t1 = "test"; //Ok!
char[] t2 = "test".dup; //Compile error
char[] t3 = "test".dup(); //Ok!
}


The problem with this approach is that you now have a pointer to mutable
data, the contents of which are stored in the static data segment, and thus
actually immutable.

Second (and this is related to the first), the pointer will be the same for
all instances, and thus changing the contents of one will change the
contents of all.

IOW, what one (probably) wants in this situation, is a constructor.




Thanks man, this is a big error of mine. Trying to manipulate the char[] 
does indeed do a segfault! I can't seem to find an explanation in the 
spec of how initializers are supposed to work, so I assumed incorrectly 
it would be ok.


I find it a bit disturbing that you can end up with a mutable reference 
to immutable data so easily, without casting or anything.


Re: Why it doesn't compile in D 2.0?

2010-01-16 Thread Lutger

On 01/16/2010 04:18 PM, aarti_pl wrote:

W dniu 2010-01-16 15:30, Lutger pisze:


Perhaps this is or should be a bug. You can override dup to work in ctfe:

char[] dup(string str)
{
return str.dup;
}

class Test {
string t1 = "test"; //Ok!
char[] t2 = "test".dup; //Compile error
char[] t3 = "test".dup(); //Ok!
}

The spec even mentions it under ctfe:

6. as a special case, the following properties can be executed at
compile time:
..dup
..length
..keys
..values

http://www.digitalmars.com/d/2.0/function.html



Thanks! I will use function dup() as a workaround for now, and will put
bug to bugzilla.

I still wonder what has CTFE to do with this case. Do you know?

I am asking because it's not possible in general case to initialize all
variables in classes/structs and in global namespace.
E.g. I had to use:

Serializer!(TextArchive) serializer;
static this() {
serializer = new typeof(serializer);
}

to initialize serializer. I am wondering if with better CTFE we could
get it working?

BR
Marcin Kuszczak
(aarti_pl)


ctfe is basically a user defined extension of constant folding, which is 
also mentioned in the spec that way. So to use it for more complex 
initialization makes sense, but this is constrained to compile time. 
From the example of the serializer, all we know is that it allocates 
memory. Array dup-ing also allocates memory however, so theoretically I 
see no immediate reason why it would not (eventually) be possible to use 
ctfe in that case. But it may be difficult to prove statically by the 
compiler that it is indeed safe to do so.


Re: Why it doesn't compile in D 2.0?

2010-01-16 Thread Lutger

On 01/16/2010 02:01 PM, aarti_pl wrote:

W dniu 2010-01-16 13:26, Simen kjaeraas pisze:

aarti_pl  wrote:



class Test {
string t1 = "test"; //Ok!
char[] t2 = "test".dup; //Compile error
}

void main(char[][] args) {
}

Error:
hello.d(3): Error: cannot evaluate _adDupT((&
D12TypeInfo_Aya6__initZ),"test") at compile time
hello.d(3): Error: cannot evaluate _adDupT((&
D12TypeInfo_Aya6__initZ),"test") at compile time

Is there workaround?


Constant strings are saved in the static data segment of the
executable, so
the .dup call would need to be executed at runtime. In other words, what
this would do is cast const to mutable.

If this did compile, changing the contents of t2 would change those
contents
for all instances of Test, which I assume is not your intention.

As for the workaround, write a constructor:

class Test {
string t1 = "test";
string t2;

this( ) {
t2 = "test".dup;
}
}



I want just simple initialization of variable. Casting of course is no
(sane) option.

Indeed, in case of classes your workaround will work.

But in case of struct? The same problem occurs for structs, but you can
not declare default constructor in structs...

IMHO .dup should work for initialization of classes/structs.

Any other ideas?

BR
Marcin Kuszczak
(aarti_pl)


Perhaps this is or should be a bug. You can override dup to work in ctfe:

char[] dup(string str)
{
return str.dup;
}

class Test {
string t1 = "test";//Ok!
char[] t2 = "test".dup;//Compile error
char[] t3 = "test".dup();  //Ok!
}

The spec even mentions it under ctfe:

6. as a special case, the following properties can be executed at 
compile time:

.dup
.length
.keys
.values

http://www.digitalmars.com/d/2.0/function.html






Re: Getting overloads for non-member functions

2010-01-15 Thread Lutger

On 01/14/2010 11:38 PM, Simen kjaeraas wrote:

Is there a way to get a list of overloads for a function name in D?

For member functions, there's __traits( getVirtualFunctions, ... ), but
that don't work for free functions.




I'm afraid there is no way. See also this blog:

http://kirkmcdonald.blogspot.com/2007/07/inadequacies-of-traits.html


Re: Call diagram generation

2010-01-03 Thread Lutger

On 01/03/2010 04:31 AM, Strt wrote:

How can I generate some sort of call diagram from my D code?


you can compile with (dmd) -profile and run the executable. This 
produces a file called trace.log which contains timings for each 
function and a call graph. It doesn't produce a diagram and has mangled 
symbols though.


You can demangle with std.demangle, read the trace.log with descent or 
use this utility:

http://www.dsource.org/projects/scrapple/wiki/PtraceUtility

I haven't updated ptrace in quite a while, so I'm not sure if it still 
works.




Re: ctfe: .idup on static array and static variables

2009-12-14 Thread Lutger
Thanks, I filed this bug for the .idup issue: 
http://d.puremagic.com/issues/show_bug.cgi?id=3615



ctfe: .idup on static array and static variables

2009-12-13 Thread Lutger
i have two question related to ctfe:

1) returning .idup on local static arrays fail but I don't understand why 
that should be: 

string foo()
{
char[1] d;
d[0] = 'd';
return d.idup;
}

pragma(msg, foo()); // "Error: cannot evaluate foo() at compile time"


.idup is not mentioned in the section on ctfe in the specs. Should this be 
filed as a bug, enhancement request or is it my error?

2) the spec says "expressions in the function may not reference any local 
static variables". However, immutable local static variables do seem to 
work, like this silly example:


string getDigit(int digit)
{
static immutable(char[10]) digits = "0123456789";
string result;
result ~= digits[digit];
return result;
}

static assert( getDigit(0) == "0" );


Is this ok? 





Re: Immutable data not copied

2009-12-09 Thread Lutger
Tomek Sowiński wrote:

> const(FAQ) says: "When doing a deep copy of a data structure, the
> invariant portions need not be copied."
> I'm trying to imagine what code would benefit from such optimization.
> 
> immutable struct Large { whole lotta data... }
> 
> struct Other { Large l; }
> 
> void funkcja(Large s);  // no reference annotation on parameter, copied?
> {
> Large t = s;   // copied?
> auto other = Other(s);  // copied?
> Other o = other;  // other.l copied?
> }
> 
> 
> Tomek

As Simen kjaeraas said, deep copy is about following references. The 
optimization mentioned in the faq is not something done automatically by the 
compiler, but merely made possible by immutable. Here is a naive example:

class ImageEditDocument
{
immutable(Image)[] layers;
}

Making a copy of such a document for further editing would normally require 
copying all images in the layers array. If they are immutable, you can just 
copy the references because you know the images will never be modified.



Re: static arrays in C functions

2009-12-08 Thread Lutger
Steven Schveighoffer wrote:

> On Tue, 08 Dec 2009 11:53:12 -0500, Bill Baxter  wrote:
> 
>> On Tue, Dec 8, 2009 at 2:08 AM, Lutger 
>> wrote:
>>> Since a while some extern(C) functions which take arrays seem to be
>>> broken.
>>> Can anybody clarify /confirm how they should be declared?
>>>
>>> For example I stumbled upon this:
>>>
>>> import core.sys.posix.unistd, std.stdio;
>>>
>>> void main()
>>> {
>>>int[2] fd;
>>>writeln( pipe(fd) ); // failes with errno == EFAULT
>>> }
>>>
>>> In core.sys.posix.unistd, pipe is declared as: int pipe(int[2]);
>>>
>>>
>>> This works though:
>>>
>>> extern (C) { int pipe(int*); }
>>>
>>> void main()
>>> {
>>>int[2] fd;
>>>writeln( pipe(fd.ptr) );
>>> }
>>
>> (Assuming you're talking about D2 here...)
>> A few releases ago fixed-size arrays changed to be pass-by-value.
>> But I guess there's still some logic in there to interpret int[2] as
>> int* when inside an extern(C) block.
> 
> No it compiles *because* that logic is not there.  It now thinks int[2] is
> a pass-by-value entity.  It links because you are using C linkage which
> does not do name-mangling.  I could define pipe as:
> 
> extern (C) int pipe(char c, int x, float y);
> 
> and it will still link :)

Interesting, I didn't realize that but it makes sense!

> 
>> It does seem like there's a bug there, though.  I think pipe(fd) in
>> the first case should fail to compile because it's attempting to pass
>> by value where a pointer is expected.
> 
> The error is either:
> 
> a) you now need to declare C functions that were declared in C taking an
> array to taking a pointer, so core.sys.posix.unistd (and likely others)
> needs to be fixed.
> b) as you suggested, inside a C block, int[2] should be interpreted as int
> *.
> 
> I'd prefer a, because I don't care much about direct translation of C
> headers :)  If b is chosen as a solution, I'd also like to have the
> compiler automatically pass the pointer when calling a C function.
> 
> -Steve

Thanks for the explanation, looks like there is some work to do in the 
binding department. This looks like a case where a piece of C code silently  
does something different in D.


static arrays in C functions

2009-12-08 Thread Lutger
Since a while some extern(C) functions which take arrays seem to be broken. 
Can anybody clarify /confirm how they should be declared? 

For example I stumbled upon this:

import core.sys.posix.unistd, std.stdio;

void main()
{
int[2] fd;
writeln( pipe(fd) ); // failes with errno == EFAULT
}

In core.sys.posix.unistd, pipe is declared as: int pipe(int[2]);


This works though:

extern (C) { int pipe(int*); }

void main()
{
int[2] fd;
writeln( pipe(fd.ptr) ); 
}




Re: Question about contracts on methods.

2009-11-28 Thread Lutger
Peter C. Chapin wrote:

> Hi!
> 
> I'm rather new to D and I'm experimenting with its support for
> contracts. I'm using dmd v1.51 on Windows.
> 
> Whenever I learn a new language I usually start by implementing a few
> "classic" components to get a feeling for how the language's features
> work in a pseudo-realistic setting. A class representing calendar dates
> is one of my favorite exercises. Here is a method next() of such a class
> that advances a Date to the next date on the calendar.
> 
> class Date {
> 
> // etc...
> 
> void next()
> {
> if (day_m != days_in_month()) ++day_m;
> else {
> day_m = 1;
> if (month_m != 12) ++month_m;
> else {
> month_m = 1;
> ++year_m;
> }
> }
> }
> }
> 
> The method days_in_month() is a private method in the class that returns
> the number of days in the "current" month. The fields day_m, month_m,
> and year_m are also private with the obvious meaning.
> 
> Okay, so far so good. Now I want to add a post condition on this method
> asserting that the date it computes is actually later than the original
> date. In my post condition I will need to access both the new values of
> day_m, month_m and year_m *and* the original values of those fields.
> There doesn't seem to be an easy way to do that.
> 
> I appreciate that I might need to explictly make my own copies of the
> original field values, but it seems like I can't do that locally in next
> () because there is no place to declare the copies where they would be
> in scope in the post condition. Do I have to add three additional fields
> to the class itself and then copy the original values in the body of
> next()? Like this:
> 
> class Date {
> 
> private {
> int original_day_m;
> int original_month_m;
> int original_year_m;
> }
> 
> void next()
> out {
> assert(
> day_m > original_day_m ||
>(day_m == 1 && month_m > original_month_m) ||
>(day_m == 1 && month_m == 1 && year_m > original_year_m));
> }
> body {
> original_day_m   = day_m;
> original_month_m = month_m;
> original_year_m  = year_m;
> 
> if (day_m != days_in_month()) ++day_m;
> else {
> day_m = 1;
> if (month_m != 12) ++month_m;
> else {
> month_m = 1;
> ++year_m;
> }
> }
> }
> }
> 
> Not only does this seem awkward it has the disadvantage that there is
> now code related to the post conditions that won't be compiled out in
> the release build. Am I missing something? Surely this situation comes
> up often.
> 
> Peter

You are not missing something, this is a known issue. It has been discussed 
and I believe the intention was to do something about this, but with all the 
high priorities I'm not sure when this will be solved.

As for the code that should not be compiled: this is easy to solve. If 
unittests and contracts are to be compiled in for dmd, you need to pass the 
-unittest flag to the compiler. This also sets the unittest flag, so you can 
put the extra code in a version(unittest){} block which won't get compiled 
without that flag (for a release).

Some compilers, like LDC, might make a distinction between unittests and 
contracts (not sure exactly how). You could then also choose to put the 
out() condition and supporting boilerplate code in a debug {} block instead. 
In some situations this makes sense when you want your release to check 
preconditions (caller violates the contract) but not postconditions (callee 
violates the contract).



Re: why can't structs implement interfaces?

2009-11-24 Thread Lutger
Bill Baxter wrote:

> On Tue, Nov 24, 2009 at 2:49 PM, Saaa  wrote:
>> bearophile wrote:
>>> Moritz Warning:
>>>
 If you only what a contract that certain functions are implemented,
 then it just need to be implemented in the compiler frontend.
>>>
>>> In the meantime this can be done with a template mixin, where the
>>> template statically asserts the presence of the functions/fields you
>>> want.
>>>
>>> Bye,
>>> bearophile
>>
>> I wanted to do something like this:
>>
>> class C : I {};
>> struct S : I {};
>> S s;
>> I[] i =[new C(), s ];
> 
> Yeh, that's never going to work because that's acting as a dynamic
> polymorphic interaface.  Referring polymorphically to a struct like
> that pretty much makes it not a struct anymore, and requires having
> the hidden pointer to a vtable that was mentioned.  That's what
> classes are for.
> 
> In D2 you can use "alias this" inside a class to forward things to the
> struct, though. Something like this:
> 
> class ClassWrapper(S) : I {
>S _impl;
>alias _impl this;
> }
> 
> But I somehow doubt DMD will consider methods handled by S as being an
> implementation of the interface.
> So you'll need explicit forwarding.
> 
> --bb

I can confirm that it is not possible with alias this. 

Somewhat related, template mixins can add virtual methods:

template T() { /*implementation of I*/ }
class C : I  { mixin T!(); } // adds methods in T!() as virtual methods







Re: why can't structs implement interfaces?

2009-11-24 Thread Lutger
Saaa wrote:

> struct S : Pos {}
> Why is this not possible?
> 
> 

Because structs are meant to be value types and thus do not implement 
dynamic polymorphism, which is what interfaces are used for.  It is not 
necessary though, classes in C++ are almost the same as structs for example, 
but there are problems with that design.

 


Re: Automatic getter/setter generation

2009-10-22 Thread Lutger
Lutger wrote:
...
> 
> mixin var!(DefaultImplementation(int, "_name")
> mixin var!(LoggingImplementation(int, "_name")
> mixin var!(UndoRedoImplementation(int, "_name")

Sorry, these would be:

mixin var!(UndoRedoImplementation, int, "_name") etc.

where UndoRedoImplementation is an alias





Re: Automatic getter/setter generation

2009-10-22 Thread Lutger
Saaa wrote:

> I was thinking about using a template which would generate a variable and
> its getters/setters automatically.
> Something like this:
> 
> mixin var!(int,"_name","rwr-");
> 
> // private int _name
> // public int name(){return _name};
> // protected void name(int value){_name=value};
> 
> What do you think about something like that?

I'm not sure it is very useful. I can think of a couple of reasons to define 
simple getter / setters:

- must be done when implementing an interface
- binary compatibility perhaps (again: interfaces)
- you will or might add functionality to the get/set functions at a later 
stage. 

If these are the only reasons, I would just go ahead and implement the 
get/set functions manually. Then again it may be useful depending on your 
application. 

One more thing you could use this for is adding functionality to get/set 
functions:

template DefaultImplementation(T, string name)
template LoggingImplementation(T, string name)
template UndoRedoImplementation(T, string name)

mixin var!(DefaultImplementation(int, "_name")
mixin var!(LoggingImplementation(int, "_name")
mixin var!(UndoRedoImplementation(int, "_name")










Re: Installing D1 and D2 side by side on linux

2009-10-14 Thread Lutger
Justin Johansson wrote:

> I got motivated by Walter putting out latest cuts of D1 and D2 (a D2
> update in less than a week recently!), so ...
> 
> Rather than having a single global install of DMD for linux, I'd like to
> have both D1 and D2 installed (i.e. distros unzipped into)
> /opt/dmd1 and /opt/dmd2 respectively
> 
> and then be able to envoke rdmd on either version using the full path to
> the executable.
> 
> Unfortunately seems like this doesn't work and rdmd can't find dmd in
> either case:
> 
> D1
> 
> /opt/dmd1/linux/bin/rdmd test.d
> sh: dmd: not found
> 
> D2
> 
> /opt/dmd2/linux/bin/rdmd test.d
> sh: dmd: not found
> sh: dmd: not found
> 
> So what's the best way to do a side-by-side install of D1 and D2 on linux?
> 
> As usual, thanks for all kind assistance,
> 
> -- Justin Johansson

I'm not sure what the best way is, but this is my setup:

somewhere in ~/ lie all versions of d I have installed: 
~/dev/dmd1045
~/dev/dmd2032
~/dev/dmd2034

etc.

Then there is one symlink ~/dev/dmd to one of those paths I want to work. I 
have ~/dmd/bin/ on the PATH. Finally there is a little script I can invoke 
like this: 'setupD dmd2032' that changes the symlink, possible remove tmp 
files used by rdmd etc.

This has worked well for me, I usually just keep the older versions in there 
too, sometimes it is useful.


Re: Getting overloads of free functions

2009-10-13 Thread Lutger
Christopher Wright wrote:

> Lutger wrote:
>> Probably has been discussed before but I couldn't figure it out:
>> 
>> Is it possible to retrieve the signatures of overloaded functions (not
>> virtuals) at compile time?
> 
> No. You can't even get all the overloads of class methods at compile
> time (only non-private non-static methods, as I recall).

That sucks.


Getting overloads of free functions

2009-10-12 Thread Lutger
Probably has been discussed before but I couldn't figure it out:

Is it possible to retrieve the signatures of overloaded functions (not 
virtuals) at compile time?


Re: Structs by ref in D2

2009-08-21 Thread Lutger
By const ref seems reasonable to allow, but by ref is bug prone. Why is it 
handy? 



alias foo.bar this?

2009-08-21 Thread Lutger
The following doesn't compile, I was wondering whether this is a temporary 
limitation, bug or by design? 

struct Bar
{
int baz;
}

struct Foo
{
Bar bar;
alias bar.baz this; // error
}





Re: Partial template function specialization

2009-08-20 Thread Lutger
You can also do this with template constraints in D2:

template foo(T, U)
if ( is(T == int) )
{
void foo(T t, U u)
{
//t is int
}
}

template foo(T, U)
if ( is(T == string) )
{
void foo(T t, U u)
{
//t is string
}
}


IFTI still works here: foo("bla", 1) and foo(1,1) are both valid

You can do almost anything in the if condition (constraint) that can 
evaluate to bool at compile time. See std.traits and the __traits keywords 
for useful stuff.



Re: setAssertHandler (druntime) segfaults

2009-07-24 Thread Lutger
http://d.puremagic.com/issues/show_bug.cgi?id=3208




Re: setAssertHandler (druntime) segfaults

2009-07-24 Thread Lutger
Jarrett Billingsley wrote:

> On Fri, Jul 24, 2009 at 4:37 PM, Lutger
> wrote:
>> There is a function setAssertHandler in druntime, but when I try to use
>> it it segfaults. I'm not sure how it should be used, this is a complete
>> example of what I try to do:
>>
>> import std.stdio;
>> import core.exception;
>>
>> void handleAssertion(string file, size_t line, string msg = null)
>> {
>> writefln("assert in %s at line %s", file, line);
>> };
>>
>> static this()
>> {
>> setAssertHandler( &handleAssertion  );
>> }
>>
>> unittest { assert(false); }
>>
>> void main() {}
>>
>>
>> output:
>> assert in test at line 16
>> Segmentation fault
>>
>> This is with dmd 2.031 on linux. Is this a bug, am I doing something
>> wrong?
> 
> Hm, it might - and I'm just taking a wild guess here - be that
> std.stdio hasn't yet been initialized when you do the writefln in your
> assertion handler.  But you really should try using a debugger to get
> a stacktrace.

Ok I tried. Funny thing, with -g enabled it doesn't segfault anymore. 
Without -g, the trace is not intelligible to me. Segfault also occurs when 
commenting out writefln.

This is useless I assume but anyway, this is what gdb gives me:

#0  0x0805292e in _TMP257 ()
#1  0x000e in ?? ()
#2  0xd02c in ?? ()
#3  0x08048f79 in _D4test11__unittest1FZv ()
Backtrace stopped: previous frame inner to this frame (corrupt stack?)
 



setAssertHandler (druntime) segfaults

2009-07-24 Thread Lutger
There is a function setAssertHandler in druntime, but when I try to use it 
it segfaults. I'm not sure how it should be used, this is a complete example 
of what I try to do:

import std.stdio;
import core.exception;

void handleAssertion(string file, size_t line, string msg = null)
{
writefln("assert in %s at line %s", file, line);
};

static this()
{
setAssertHandler( &handleAssertion  );
}

unittest { assert(false); }

void main() {}


output:
assert in test at line 16
Segmentation fault

This is with dmd 2.031 on linux. Is this a bug, am I doing something wrong? 




Re: How to see result of a mixin? (equivalent of running C preprocessor)

2009-07-24 Thread Lutger
asd wrote:

> I'm trying to get D-ObjC bridge working and I'm getting weird errors
> triggered somewhere deeply in a mix of templates and mixins that's too
> hard for me to understand.
> 
> How can I analyze such problem in D? Is it possible to tell dmd to run
> only compile-time functions/templates and output that as a D source?

Not directly except with descent. It's worth it to try descent compile time 
debugger (and compile time view!), really awesome stuff. 

Other than that, you can use pragma(msg, ...) where you have several options 
for ... depending on what you want to debug and whether it's D1 or D2. 
.stringof property and typeof() are useful for this. Take a look at 
std.traits and for D2 at __traits. Generally the error messages with such 
code is not so friendly. 

String mixins can also just be printed with writeln / Stdout.







Re: Regex

2009-07-11 Thread Lutger
BLS wrote:

> Robert Fraser wrote:
>> BLS wrote:
>>> Vladimir Voinkov wrote:
 std.regex can't be used in compile time function call. It's quite
 frustrating...
>>>
>>> see dsource.org .. afaik there is a compile time regex project. hth
>> 
>> http://www.dsource.org/projects/scregexp
>> 
>> But the generated functions aren't CTFE-compatible AFAIK. A CTFE regex
>> engine would be um... "tricky" to say the least. About 50GB of memory
>> tricky (on DMD, LDC has a GC... though, it's still just as slow with
>> CTFE). Really, if you need that level of code manipulation, a
>> preprocessor is probably a better choice.
> 
> Ouch!
> Remaining question :
>  >>> std.regex can't be used in compile time function call
> 
> Why this* don't work for you ?
> *  http://www.digitalmars.com/d/2.0/templates-revisited.html
> (middle of the document / Regular Expression Compiler)

Because it compiles the regex, but matching is still done at runtime? Or is 
it CTFE compilable? iirc CTFE wasn't around at the time this regex compiler 
was written.



Re: Template limits in D2

2009-05-24 Thread Lutger
Ary Borenszweig wrote:
...
> 
> BTW, I had to debug inside Descent's code to find this. If I debug it 
> using the debugger I'm programming, I can see it stops the execution 
> right at the "s.a[i] = m;" line, without saying why (DMD doesn't say 
> why). It's not much, but I think it's better than "Can't evaluate at 
> compile-time", and might give you more clues about it. :-)

yes it's this: "s.a[i] = m", it doesn't work with dynamic arrays either. 



Re: Template limits in D2

2009-05-24 Thread Lutger
bearophile wrote:

... 
> 
> The second problem is that compile-time functions are nicer, so I'd like to 
> not use templates when possible. But the following code doesn't work at 
> compile time, can you tell me why? (I have had to use a 
not nice temporary struct to return the static array)
> 
> struct S(int N) { int[N] a; }
> 
> S!(N) genSquares(int N)() {
> S!(N) s;
> for (int i = 0; i < N; i++) {
> int n = i;
> int m = 0;
> while (n) {
> int digit = n % 10;
> n /= 10;
> m += digit * digit;
> }
> s.a[i] = m;
> }
> 
> return s;
> }
> void main() {
> const int CHUNK = 1000;
> static const auto squares = genSquares!(CHUNK)().a;
> }
> 
> Bye and thank you,
> bearophile

I'm not sure why, this code does work:

int[] genSquares(int N)()
{
int[] a;

for (int i = 0; i < N; i++)
{
int n = i;
int m = 0;

while (n)
{
int digit = n % 10;
n /= 10;
m += digit * digit;
}
a~=m;
}
return a;
}

void main() {
enum int CHUNK = 1000;
enum int[CHUNK] squares = genSquares!(CHUNK)();
}

However, it fails as soon as I try do use indexing or set the length of an 
array. I thought these operations were supposed to be legal, perhaps it is a 
bug.




Re: Need direction guide

2009-05-04 Thread Lutger
Sam Hu wrote:

> I have learnt C++ for years and can write simple and short toys.I have 
been following and learning D for quite a while but I can do nothing except 
finding ppl like you giant seems just write libs at this moment.I believe D2 
is getting mre powerful and stronger but it seems to me just a legend.So 
right at this moment,I am wondering:
> 1.Whether D1 is useful to do something,or it is quite worth to wait for 
the stable or "finalized" verison of D2?If yes,what can one do using D1,I 
mean not just a toy,a test product,rather an serious tool?

D1 is very useful and mature imho, you can do anything with it that it was 
designed for and them some more. 

The choice of D1 or D2 is not too difficult: D2 itself is still changing, 
compiler may have more bugs, and there are very, very few libraries for it. 
Even the dsss build tool does not work with latest versions of dmd2. This 
means: only usable for learning, building libraries and generally if you 
want to stay on top of the bleeding edge. Not so suitable for making 
applications yet.

> 2.Are those feathers in D2 vital  while D1 does not have?Or all these 
features are just for experienced programmers,a beginner can just ignore 
them at present?

Both are true I think. They really are important improvements, but not in a  
way that makes D1 incomplete without them. 
 
> I am lost although I like D so much than C++.I would like to spend as much 
time as learning C++ and want to gain as much as gain C++ can offer me.Any 
constructive suggestions or guideline would be much appreicated.
> 
> Regards,
> Sam

Is your goal for now *just* to learn D? Then you could start making toy 
programs with D2. Is your goal to learn D and make some cool programs? Then 
D1 will make that easier. 

Happy programming!




Re: D styled data format, Json failed

2009-05-04 Thread Lutger
Saaa wrote:

> 
> I looked at the JSON format and it seems very inefficient at loading 
arrays 
> as it isn't limited to one type per array.
> This is nice when you want to save a small array with different typed 
> elements but for my purposes this is kind of a performance problem.
> 
> This is why I will try and get suggestions again about the D-styled format 
I 
> tried to suggest a few threads ago :)
> 
> Let me suggest a simple example:
> (Please tell me when something isn't obvious :)
> 

I guess you will have to write this one yourself, it will be to D what JSON 
is to javascript ;)

I wonder how much of an performance improvement you will get though when 
loading data at runtime. You still have to parse and check everything since 
it remains a text based format. 

I know of one other solution but that's again not available for D: google 
protobuf: http://code.google.com/p/protobuf/
This uses a text-based format for describing the structure of the data, but 
the actual data can be in an optimized binary format.






Re: D-styled data file

2009-04-29 Thread Lutger
Saaa wrote:

> I would like to be able to read and write variables which are human 
> readable.
> It should be as fast as possible and easy to use.
> 
...
> --
> 
> Any comments, questions or pointers?
> Maybe all this is already available?
> I would think that the parsing code is already available somewhere.

JSON is a very nice format for this and Tango has a parser for it. Yaml is 
even easier imho, but there are no D parsers for it yet.




Re: What is the sate of LDC?

2009-03-24 Thread Lutger
bearophile wrote:

..
> (Eventually I'd like to see a project like dlang, a D clang-like front-end 
for LLVM written in D, replace LDC, but this will require a ton of work. So 
it's mostly a dream now).

Sounds like dil: http://code.google.com/p/dil/



Re: getting mutable type from T

2009-03-24 Thread Lutger
Jarrett Billingsley wrote:
..
> std.traits.Mutable!(T).

Ah thanks! Too obvious.

In case somebody would like to know:

static if (is(T U == const(U)))
alias U Mutable;
else static if (is(T U == immutable(U)))
alias U Mutable;




getting mutable type from T

2009-03-24 Thread Lutger
How can I get the mutable type from any type T in a generic function or 
template, assuming T is const or immutable?




Re: Char[] confusing

2009-03-02 Thread Lutger
Qian Xu wrote:

> Hi,
> 
> I am confusing with getting sub-string of a char[].
> 
> - code -
> module main;
> 
> import tango.io.Console;
> import tango.text.convert.Integer;
> 
> void main()
> {
>char[] s = "ABCDE"; // 5 chars
>int len = s.length;
>Cout("s='" ~ s ~ "', length=" ~ toString(len)).newline;
>Cout("s[" ~ toString(len-1) ~ "]= " ~ s[len-1]).newline;
>Cout("s[0 .. " ~ toString(len-1) ~ "]= " ~ s[0 .. len-1]).newline;
>Cout("s[0 .. " ~ toString(len) ~ "]= " ~ s[0 .. len]).newline;
>Cout("s[1 .. " ~ toString(len-1) ~ "]= " ~ s[1 .. len-1]).newline;
>Cout("s[1 .. " ~ toString(len) ~ "]= " ~ s[1 .. len]).newline;
> }
> - code -
> 
> The result is (dmd + windowsxp)
> 
> s='ABCDE', length=5
> s[4]= E
> s[0 .. 4]= ABCD
> s[0 .. 5]= ABCDE
> s[1 .. 4]= BCD
> s[1 .. 5]= BCDE
> 
> ---
> 
> My question is: why s[4]=E, but s[0..4]=ABCD (without E)

s[4] means the fifth element of s[]
s[0..4] is a slice from the first to the fifth, but not including the fifth 
element. The last element in a slice is always one past the end of that 
slice. 



Re: CUDA with D?

2009-03-01 Thread Lutger
Chris R Miller wrote:
...
> 
> I looked into OpenCL, which appears (at first glance) to be a funky way 
> of stringing together assembler instructions using C function calls. 
> I'm sure it's fast, but it's not the most friendly looking code to me 
> (then again, I don't know ASM, so what do I know?)

It's at a higher level than that, basically shaders for more general purpose 
parallel computation BUT: the OpenCL runtime is supposed to take that code 
and load balance it over whatever processors it can find in your system, 
GPU's, multiple cores with or without SIMD instructions, whatever. 




solved

2009-02-28 Thread Lutger
Can't believe it's happening again, I found the problem after posting.

Due to a kernel update mess I found out my Suse mounted some partitions in 
fstab as 'user' by default, which means noexec apparently . In the funky way 
I separated my drives and partitions this caused some commands to be 
unexecutable. 

Sorry for the noise. 



Re: finding dmd.conf

2009-02-28 Thread Lutger
Jesse Phillips wrote:

> On Fri, 27 Feb 2009 15:54:46 +0100, Lutger wrote:
> 
>> I'm having some trouble with dmd.conf. I set up a (soft) symbolic link
>> to the dmd/bin path version I want to use, but dmd can't find
>> dmd.conf:
>> 
>> $> which dmd
>> /home/lutger/code/bin/dmd/bin/dmd
>> $> dmd main.d
>> object.d: module object cannot read file 'object.d' $>
>> /home/lutger/code/bin/dmd/bin/dmd main.d $>
>> 
>> Fully specifying the path works, and putting dmd.conf in /etc also
>> works, but is less than ideal. This is in bash (Konsole) on OpenSuse
>> 11.1.
>> 
>> Anybody an idea what I am doing wrong?
> 
> I'm not sure what you mean by "symbolic link to the dmdxxxx/bin path 
> version I want..."
> 
> DMD looks in only 2 places for dmd.conf, the location of the dmd 
> executable, in your case /home/lutger/code/bin/dmd/bin/, and /etc/

It also looks in HOME and the current directory.

I should have explained clearer. I have setup 3 installations of D that I 
use:

~/code/bin/dmd1033/bin
~/code/bin/dmd1037/bin
~/code/bin/dmd2025/bin

Then I make a symbolic link to one a these paths:
~/code/bin/dmd/bin

The symbolic link is in PATH. This way I can easily switch between whatever 
d executables, libraries and so forth as required while keeping them 
seperate. 

The problem I'm experiencing is that DMD can find dmd.conf in it's own path 
only when I fully qualify the dmd command like this: ~/code/bin/dmd/bin/dmd 
main.d
Putting dmd.conf in /etc works though, and putting dmd.conf in the current 
path (of the source I'm building) also works. 

Furthermore for D1 I'm using dsss in the same way and this doesn't cause any 
problems. I thought perhaps some other dmd got picked up, but 'which dmd' 
picks out the right path for dmd, if this command is reliable?



Re: finding dmd.conf

2009-02-27 Thread Lutger
Moritz Warning wrote:
...
> Have you tried to add your dmd/bin to your PATH environment variable?

Yes it's there and dmd got properly picked up by the 'which'  command.



  1   2   >