Re: Are there any D scripting engines for use with D?

2016-01-04 Thread Max Klyga via Digitalmars-d-learn

On 2016-01-04 18:40:03 +, Jason Jeffory said:

We have many scripting engines available for use in D more or less(lua, 
python, etc...).


Is there a D scripting engine that can be easily integrated into a D 
project? A sort of "exec()". Something that works at compile 
time and run time possibly? If  is a static string then it 
should be able to compile it at compile time, else, run time. Also, it 
would be nice if one could set up a unique state for the code to run 
in(so it can't be hacked by harmful coding), e.g., "exec(, 
state)", where state is the state used for the exec(passed along to the 
 to use) for external function access and variable passing.


Something that is fast as possible would be nice too! I know there this 
is quite a request, but hopefully there will be work on it. I'd love to 
see scripting capabilities included with most programs! This would be a 
start, at least, for my programs.


The fastest one would probably be Lua - http://code.dlang.org/search?q=lua
But there are other options:
Python - http://code.dlang.org/packages/pyd
Javascript - http://code.dlang.org/search?q=javascript and 
http://pointersgonewild.com/higgs/
Croc (previously miniD, a scripting language implemented in D) - 
http://jfbillingsley.com/croc/




Re: Templates: Array slices not recognized

2015-04-18 Thread Max Klyga via Digitalmars-d-learn

On 2015-04-18 13:46:19 +, Chris said:


The following:

import std.stdio : writefln;
import std.range.primitives : isInputRange, hasLength;

void main() {
   size_t[] a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
   doSomething(a);  // works

   doSomething(a[0..5]);

// --- Error: template slices.doSomething cannot deduce function from 
argument types !()(ulong[]), candidates are:
   // slices.d(11): slices.doSomething(R)(ref R r) if (isInputRange!R 
 hasLength!R)


   doSomething!(size_t[])(a[0..5]);
   // --- Error: doSomething (ref ulong[] r) is not callable using 
argument types (ulong[])

}

void doSomething(R)(ref R r)
 if (isInputRange!R  hasLength!R)  // etc..
{
   foreach (ref n; r) {
 writefln(%d * 2 = %d, n, n * 2);
   }
}

//EOF

a[0..5] is not recognized as size_t[]. If I give the compiler a hint 
with !(size_t[]), it complains again, i.e. I can not pass the slice as 
a reference.


A workaround is

size_t[] b = a[0..5];
doSomething(b);

However, this comes with a serious performance penalty in for loops 
(even if I predefine b and reuse it in the loop). 
to!(size_t[])(a[0..5]) is even worse.


Any thoughts or tips?


a[0..5] is an R-value, and cannot be passed by reference.
As you noticed, once you use a variable - everything works because only 
L-values can be passed by reference.


Also why are you passing slices by reference? Slices do not copy the 
memory they point to when passed by value.




Re: Interlocked (compare) exchange

2015-04-17 Thread Max Klyga via Digitalmars-d-learn

On 2015-04-17 10:36:31 +, Szymon Gatner said:


Hi,

are there equivalents of Interlocked.Exchange [1] and 
Interlocked.CompareExchange [2] in D? I can't find it in teh docs?


[1] https://msdn.microsoft.com/en-us/library/f2090ex9(v=vs.110).aspx

[2] https://msdn.microsoft.com/en-us/library/h7etff8w(v=vs.110).aspx


http://dlang.org/phobos/core_atomic.html#.cas



Re: string-int[] array

2015-03-08 Thread Max Klyga via Digitalmars-d-learn

On 2015-03-08 21:11:42 +, Paul said:


On Sunday, 8 March 2015 at 18:05:33 UTC, Dennis Ritchie wrote:
Is it possible to create such an array in which you can store strings 
and numbers at the same time?


string-int[] array = [4, five];


As there's no mention of performance, what's wrong with a plain old 
string array with a bit of conversion and error checking?


string[] soup = [4, Test, 5, More Test];


OP is fighting a loosing battle in flame war on some obscure forum. F# 
enthusiast trolls OP into solving stupid puzzles that are trivial in F# 
(or any ML-family language) and clumsy in C-family languages.


In language holy wars the only winning move is not to play.



Re: Object as function argument

2015-03-05 Thread Max Klyga via Digitalmars-d-learn

On 2015-03-05 19:35:34 +, Chris Sperandio said:


Hi,

I'm a developer coming from C and I've a question about class instance 
as method or function parameter.
In the book The D Programming Language, I read the instance was 
passed by reference to functions (in the opposite of structures). I 
understood that it was the same object in the function and the caller. 
But I'm think, I was wrong because when I print the addresses of an 
object before the function call and inside the function, they're not 
the same but the changes from the function are kept in the instance.
If I use the ref qualifier in the function declaration, the 2 
addresses are the same.


How do the changes work in the function? Is there a copy ? Or a magic 
trick :) ?


Chris


When you write `auto myObject = new MyObject();`
`myObject` is actually a pointer to object in GC memory. Its roughly 
equivalent to `struct MyObject *myobject` in C. So when you take a 
pointer you actually take a pointer to reference on the stack and thats 
why its different in the function - variable is higher up the stack.

`ref` qualifyer guaranties that you get the pointer to the same reference.

If you really need the actual pointer to object data you can use 
`*cast(void**)myObject`. Compiler cannot cast object reference to 
`void*` but we can trick it ;)




Re: Insert if doesn't exist without double lookup.

2014-03-15 Thread Max Klyga

On 2014-03-15 18:44:46 +, Agustin said:


Hello!, i would like to know if this is possible.

auto asValue ?= (map[Key] == new Value);

Instead of doing:

if ((Key in map) is null)
map[Key] = new Value
auto asValue = map[Key];


auto needle = Key in map;
auto value = needle ? *needle : (map[Key] = new Value);



Re: Binary Data Serialization Libraries

2013-12-06 Thread Max Klyga

On 2013-12-06 13:33:44 +, Jeroen Bollen said:

Are there any Binary Data Serialization Libraries available written in 
D2? I'm looking for something like a BSON read/write library. (Although 
can be any other binary language really)


MessagePack - format very similar to BSON - 
https://github.com/msgpack/msgpack-d




Re: Monads compared to InputRanges?

2013-12-04 Thread Max Klyga

On Wednesday, 4 December 2013 at 10:03:51 UTC, Timon Gehr wrote:

On 12/04/2013 12:49 AM, Max Klyga wrote:



range.map(...).flatten.map(...) might look similar and it 
could be
possible to squeeze monads to work with this api,  but the 
thing is that

not every monad could provide a meaningful map function


Yes, every monad provides a meaningful way to map morphisms.

In Haskell this is not explicit however:

map :: Monad m = (a - b) - m a - m b
map f = (return . f =)


and as a whole
calling flatten after every map is a bit tiresome.


You are right. Now looking at provided implementation this seems 
obvoius


Re: Monads compared to InputRanges?

2013-12-04 Thread Max Klyga

On Wednesday, 4 December 2013 at 08:24:03 UTC, qznc wrote:
On Wednesday, 4 December 2013 at 01:53:39 UTC, Shammah 
Chancellor wrote:

Or is D syntax not generic enough to define monads?


I started to port monads to D [0]. You can do it, but it looks 
ugly. The trick is to implement (Haskell) type classes via 
template specialization. I came to the conclusion that it is 
not worth it.


What D kind of lacks is a way to define a general type class 
aka the interface. Of course, you could use the interface 
keyword, but then you cannot apply it to structs. Haskell has 
no structs (value type records), so they do not have this 
problem. Look at how isInputRange is implemented [1]. The 
traits in Rust [2] provide this interface mechanisms as a 
language feature. D uses static-if instead.


D uses static if and template constraints for typeclass/concept 
checking because one cannot add specializations to templates 
defined in other modules. Using template specialization for 
defining type class instances would render them not extensible 
for users


Re: Monads compared to InputRanges?

2013-12-03 Thread Max Klyga

On 2013-12-03 02:45:44 +, Shammah Chancellor said:

I'm not particularly familiar with the syntax being used in the variet 
of monad examples.   I'm trying to figure out how this is different 
from UFCS on InputRanges.   It seems like std.algorithm implements 
something which accomplished the same thing, but much easier to 
understand?


Can somebody maybe do a compare and contrast for me?

-Shammah


Monads and input ranges are different things. I'll try to briefly 
explain monads. Hope this will not worsen the situation by being too 
confusing.


InputRanges provide a generic way for iterating over something.

UFCS can be used to create a range interface on things that do not provide it.

Monads are an abstraction for composing things within some context 
(concatenating lists, composing operations on nullable values, 
composing asynchronous operations). That sounds a bit too general and 
vague, because it is. One can think about as a design pattern.

Monad has two operations:
 - make a monad out of a value
 - apply a function that takes a value and returns a new monad of the 
same kind to value inside a monad


second operation has a different meaning for different monad kinds but 
generally it means 'execute this code within current context'


for nullable values this means 'execute only if there exist a value'
for asynchronous operations this means 'execute this when the value is ready'

This operation is commonly named 'bind' or 'flatMap'

Some languages provide syntax sugar for monads (Scala's for, Haskell's do)
Monads are easier to understand once you've seen enough examples of 
things that are monads.


Suppose you have a list of movies and want to produce a list of names 
of all actors stating in those movies.

In scala you would typically write something like this:

for (movie - movies; actor - movie.actors) yield actor.name

Compiler rewrites that to

movies.flatMap(movie = movie.actors).map(actor = actor.name)
  ^
   -- this function takes a list 
element and returns a new list, effectively creating a list of lists 
and then flattening it by concatenating all the lists into one, hence 
the name 'flatMap'. It transforms and then flattens.


Another popular example for Monads are optional values (similar to 
nullables but forcing you to check for presence of value and explicitly 
avoiding null dereferencing)


A common pattern for working with optional values is returning null 
from your function if your input is null


So if say we are parsing JSON and we want to process only values that 
contain certain field, that in turn contains another field. Example in 
pseudo-scala:


	for (value - json.get(value); // type of value is Option(JsonNode) 
meaning that actual json node might be absent
	   anotherValue - value.get(another)) // this is executed only 
if value is present

doSomethingFancy(anotherValue) // ditto

and again, compiler will rewrite this into

	json.get(value).flatMap(value = 
value.get(another)).foreach(anotherValue = 
doSomethingFancy(anotherValue))


Once again we see that flat map is used. The pattern is same - get the 
value out of the box, transform it to another box of the same kind in 
the context meaningful for this particular box kind


So the main benefit is being able to compose things in a consistent 
way. Once you grasp the whole idea its fun finding out that some thing 
you've been doing can be viewed as a monad. People created quite a lot 
of different monads to this date.




Re: Monads compared to InputRanges?

2013-12-03 Thread Max Klyga

On 2013-12-03 23:02:13 +, Shammah Chancellor said:


On 2013-12-03 21:51:20 +, Max Klyga said:


On 2013-12-03 02:45:44 +, Shammah Chancellor said:

I'm not particularly familiar with the syntax being used in the variet 
of monad examples.   I'm trying to figure out how this is different 
from UFCS on InputRanges.   It seems like std.algorithm implements 
something which accomplished the same thing, but much easier to 
understand?


Can somebody maybe do a compare and contrast for me?

-Shammah


Monads and input ranges are different things. I'll try to briefly 
explain monads. Hope this will not worsen the situation by being too 
confusing.


InputRanges provide a generic way for iterating over something.

UFCS can be used to create a range interface on things that do not provide it.

Monads are an abstraction for composing things within some context 
(concatenating lists, composing operations on nullable values, 
composing asynchronous operations). That sounds a bit too general and 
vague, because it is. One can think about as a design pattern.

Monad has two operations:
 - make a monad out of a value
 - apply a function that takes a value and returns a new monad of the 
same kind to value inside a monad


second operation has a different meaning for different monad kinds but 
generally it means 'execute this code within current context'


for nullable values this means 'execute only if there exist a value'
for asynchronous operations this means 'execute this when the value is ready'

This operation is commonly named 'bind' or 'flatMap'

Some languages provide syntax sugar for monads (Scala's for, Haskell's do)
Monads are easier to understand once you've seen enough examples of 
things that are monads.


Suppose you have a list of movies and want to produce a list of names 
of all actors stating in those movies.

In scala you would typically write something like this:

for (movie - movies; actor - movie.actors) yield actor.name

Compiler rewrites that to

movies.flatMap(movie = movie.actors).map(actor = actor.name)
  ^
   -- this function takes a list 
element and returns a new list, effectively creating a list of lists 
and then flattening it by concatenating all the lists into one, hence 
the name 'flatMap'. It transforms and then flattens.


Another popular example for Monads are optional values (similar to 
nullables but forcing you to check for presence of value and explicitly 
avoiding null dereferencing)


A common pattern for working with optional values is returning null 
from your function if your input is null


So if say we are parsing JSON and we want to process only values that 
contain certain field, that in turn contains another field. Example in 
pseudo-scala:


	for (value - json.get(value); // type of value is Option(JsonNode) 
meaning that actual json node might be absent
	   anotherValue - value.get(another)) // this is executed only 
if value is present

doSomethingFancy(anotherValue) // ditto

and again, compiler will rewrite this into

	json.get(value).flatMap(value = 
value.get(another)).foreach(anotherValue = 
doSomethingFancy(anotherValue))


Once again we see that flat map is used. The pattern is same - get the 
value out of the box, transform it to another box of the same kind in 
the context meaningful for this particular box kind


So the main benefit is being able to compose things in a consistent 
way. Once you grasp the whole idea its fun finding out that some thing 
you've been doing can be viewed as a monad. People created quite a lot 
of different monads to this date.



I get the gist of that, but it seems like the range concept with UFCS 
provides the same thing? E.G.  range.map().flatten().map()?


Does it really not accomplish the same thing -- am I missing some key 
point of monads?


You look only at the syntax side of the question.

range.map(...).flatten.map(...) might look similar and it could be 
possible to squeeze monads to work with this api, but the thing is that 
not every monad could provide a meaningful map function and as a whole 
calling flatten after every map is a bit tiresome.


That may work for some monads, like List, because its effectively a range.
It will also work for Maybe monad. It could be viewed as a range of 0 
or 1 elements.
But things get bad when we try to define other monads in terms of range 
interface.


Current map implementation by design doesn't know anything about range 
it processes. If we try to define Promise monad as a range it will 
practically be useless unless we provide a custom map implementation 
for promises, because std.algorithm.map will return a wrapper range 
that will call popFront() that will block and wait for the value but 
that defeats the purpose entirely as we wanted the result to be mapped 
asynchronously when it will be available and not block.
What about other monads? Defining IO or State monads

Re: Monads compared to InputRanges?

2013-12-03 Thread Max Klyga

On 2013-12-04 01:53:39 +, Shammah Chancellor said:


On 2013-12-03 23:49:47 +, Max Klyga said:


On 2013-12-03 23:02:13 +, Shammah Chancellor said:


On 2013-12-03 21:51:20 +, Max Klyga said:


On 2013-12-03 02:45:44 +, Shammah Chancellor said:

I'm not particularly familiar with the syntax being used in the variet 
of monad examples.   I'm trying to figure out how this is different 
from UFCS on InputRanges.   It seems like std.algorithm implements 
something which accomplished the same thing, but much easier to 
understand?


Can somebody maybe do a compare and contrast for me?

-Shammah


Monads and input ranges are different things. I'll try to briefly 
explain monads. Hope this will not worsen the situation by being too 
confusing.


InputRanges provide a generic way for iterating over something.

UFCS can be used to create a range interface on things that do not provide it.

Monads are an abstraction for composing things within some context 
(concatenating lists, composing operations on nullable values, 
composing asynchronous operations). That sounds a bit too general and 
vague, because it is. One can think about as a design pattern.

Monad has two operations:
 - make a monad out of a value
 - apply a function that takes a value and returns a new monad of the 
same kind to value inside a monad


second operation has a different meaning for different monad kinds but 
generally it means 'execute this code within current context'


for nullable values this means 'execute only if there exist a value'
for asynchronous operations this means 'execute this when the value is ready'

This operation is commonly named 'bind' or 'flatMap'

Some languages provide syntax sugar for monads (Scala's for, Haskell's do)
Monads are easier to understand once you've seen enough examples of 
things that are monads.


Suppose you have a list of movies and want to produce a list of names 
of all actors stating in those movies.

In scala you would typically write something like this:

for (movie - movies; actor - movie.actors) yield actor.name

Compiler rewrites that to

movies.flatMap(movie = movie.actors).map(actor = actor.name)
  ^
   -- this function takes a list 
element and returns a new list, effectively creating a list of lists 
and then flattening it by concatenating all the lists into one, hence 
the name 'flatMap'. It transforms and then flattens.


Another popular example for Monads are optional values (similar to 
nullables but forcing you to check for presence of value and explicitly 
avoiding null dereferencing)


A common pattern for working with optional values is returning null 
from your function if your input is null


So if say we are parsing JSON and we want to process only values that 
contain certain field, that in turn contains another field. Example in 
pseudo-scala:


	for (value - json.get(value); // type of value is Option(JsonNode) 
meaning that actual json node might be absent
	   anotherValue - value.get(another)) // this is executed only 
if value is present

doSomethingFancy(anotherValue) // ditto

and again, compiler will rewrite this into

	json.get(value).flatMap(value = 
value.get(another)).foreach(anotherValue = 
doSomethingFancy(anotherValue))


Once again we see that flat map is used. The pattern is same - get the 
value out of the box, transform it to another box of the same kind in 
the context meaningful for this particular box kind


So the main benefit is being able to compose things in a consistent 
way. Once you grasp the whole idea its fun finding out that some thing 
you've been doing can be viewed as a monad. People created quite a lot 
of different monads to this date.



I get the gist of that, but it seems like the range concept with UFCS 
provides the same thing? E.G.  range.map().flatten().map()?


Does it really not accomplish the same thing -- am I missing some key 
point of monads?


You look only at the syntax side of the question.

range.map(...).flatten.map(...) might look similar and it could be 
possible to squeeze monads to work with this api, but the thing is that 
not every monad could provide a meaningful map function and as a whole 
calling flatten after every map is a bit tiresome.


That may work for some monads, like List, because its effectively a range.
It will also work for Maybe monad. It could be viewed as a range of 0 
or 1 elements.
But things get bad when we try to define other monads in terms of range 
interface.


Current map implementation by design doesn't know anything about range 
it processes. If we try to define Promise monad as a range it will 
practically be useless unless we provide a custom map implementation 
for promises, because std.algorithm.map will return a wrapper range 
that will call popFront() that will block and wait for the value but 
that defeats the purpose entirely as we wanted the result to be mapped

Re: OptionalT equivalent in D?

2013-11-16 Thread Max Klyga

On 2013-11-16 05:04:20 +, Jonathan M Davis said:


I really don't understand this. OptionalT is one of the most useless ideas
that I've ever seen in Java. Just use null.


Optional specifies explicitly that value can be absent and forces 
client to check before using the value.
Also, if Optional implements monadic interface one can easily chain 
computations depending on the state of optional values.


Even if references are nullable by default users do not check them for 
null on every usage. NullPointerException and the like are almost 
always indicators of programming error.


Null is just horrible.



Re: Embed JavaScript into D

2013-11-04 Thread Max Klyga

On 2013-11-04 21:20:46 +, Adam D. Ruppe said:


On Monday, 4 November 2013 at 19:35:55 UTC, Jeroen Bollen wrote:

Is there a way I can embed javascript into my D application?


You could use any C javascript lib too, but for ones already wrapped or 
something, I know there's a few D implementations of javascript: 
dmdscript http://www.digitalmars.com/dscript/index.html (written in 
D1 but there's two or three ports out there to D2)


D1 version is now on github:
https://github.com/DigitalMars/DMDScript

D2 version:
http://dsource.org/projects/dmdscript-2/
pretty sure it will need tweaks to compile with current DMD version

You could rather easyly embed Mozilla Spidermonkey engine, as it 
provides a C api and D work great with C





Re: for loop

2012-01-22 Thread Max Klyga

On 2012-01-22 16:23:36 +0300, RenatoL said:


This works:

import std.stdio;
void main()
{
int x = 0;
int y = 0;
for(; ((x  5)  (y  5)); x++, y ++)
{
writeln(x + y = , x + y);
}
}

The question is easy: is it possible to insert x and y internally
in the for header? that is something like C#

for (int x = 0, int y = 0; .)

this doesn't work in D.


If you want to declare and initialize several variables in the for 
loop, you can do it if they are of the same type:


for (int x = 0, y = 0; ...; .++x, ++y) { ... }



Re: multiple return

2011-04-19 Thread Max Klyga

On 2011-04-20 01:35:46 +0300, %u said:


I have function which have more than one return, and the code compile and run
but it gives rong result -I guess-, so i use tuple but the compiler can't
return tuple.

how can I return values?
why I can't return tuple?


In D, tuple is not built in type, it is defined in stantard library. To 
use it, you must import module std.typecons


Example:
import std.typecons;
 
struct Foo {}
 
Tuple!(int, string, Foo) baz() {
    // some computation here
    return tuple(13, inches, Foo());
}
 
void main() {
    auto bar = baz();
    assert(bar == tuple(13, inches, Foo()));
}