Strange error when sorting strings with D - sorting

I am in the process of learning D (I decided it would be a better beginner friendly language than C++) and I decided to give myself the excercise of implementing a general quicksort in D. My program runs fine when sorting integers but it doesn't compile and throws a strange error when sorting strings.
Here is my code:
import std.stdio, std.algorithm;
T[] quickSort(T)(T[] input) {
if (input.length <= 1) {return input;}
ulong i = input.length/2;
auto pivot = input[i];
input = input.remove(i);
T[] lesser = [];
T[] greater = [];
foreach (x; input) {
if (x<=pivot)
{
lesser ~= x;
}
else
{
greater ~=x;
}
}
return (quickSort(lesser) ~ cast(T)pivot ~ quickSort(greater));
}
void main() {
//Sort integers, this works fine
//writeln(quickSort([1,4,3,2,5]));
//Sort string, throws weird error
writeln(quickSort("oidfaosnuidafpsbufiadsb"));
}
When I run it on a string it throws this error:
/usr/share/dmd/src/phobos/std/algorithm.d(7397): Error: template std.algorithm.move does not match any function template declaration. Candidates are:
/usr/share/dmd/src/phobos/std/algorithm.d(1537): std.algorithm.move(T)(ref T source, ref T target)
/usr/share/dmd/src/phobos/std/algorithm.d(1630): std.algorithm.move(T)(ref T source)
/usr/share/dmd/src/phobos/std/algorithm.d(1537): Error: template std.algorithm.move cannot deduce template function from argument types !()(dchar, dchar)
/usr/share/dmd/src/phobos/std/algorithm.d(7405): Error: template std.algorithm.moveAll does not match any function template declaration. Candidates are:
/usr/share/dmd/src/phobos/std/algorithm.d(1786): std.algorithm.moveAll(Range1, Range2)(Range1 src, Range2 tgt) if (isInputRange!(Range1) && isInputRange!(Range2) && is(typeof(move(src.front, tgt.front))))
/usr/share/dmd/src/phobos/std/algorithm.d(7405): Error: template std.algorithm.moveAll(Range1, Range2)(Range1 src, Range2 tgt) if (isInputRange!(Range1) && isInputRange!(Range2) && is(typeof(move(src.front, tgt.front)))) cannot deduce template function from argument types !()(string, string)
helloworld.d(9): Error: template instance std.algorithm.remove!(cast(SwapStrategy)2, string, ulong) error instantiating
helloworld.d(31): instantiated from here: quickSort!(immutable(char))
helloworld.d(31): Error: template instance helloworld.quickSort!(immutable(char)) error instantiating

the problem is that strings are immutable so remove won't work (as it manipulates the string)
you can fix that by not removing and not inserting the pivot in the concat:
auto pivot = input[i];
//input = input.remove(i); //<- remove this line
T[] lesser = [];
//...
return (quickSort(lesser) ~ quickSort(greater)); //<- remove cast(T)pivot ~
or by passing in a dup:
writeln(quickSort("oidfaosnuidafpsbufiadsb".dup));

You have to put a "d" behind the string to make it utf-32, otherwise remove won't accept it.
writeln(quickSort("oidfaosnuidafpsbufiadsb"d.dup));

Related

Algorithm / data structure for resolving nested interpolated values in this example?

I am working on a compiler and one aspect currently is how to wait for interpolated variable names to be resolved. So I am wondering how to take a nested interpolated variable string and build some sort of simple data model/schema for unwrapping the evaluated string so to speak. Let me demonstrate.
Say we have a string like this:
foo{a{x}-{y}}-{baz{one}-{two}}-foo{c}
That has 1, 2, and 3 levels of nested interpolations in it. So essentially it should resolve something like this:
wait for x, y, one, two, and c to resolve.
when both x and y resolve, then resolve a{x}-{y} immediately.
when both one and two resolve, resolve baz{one}-{two}.
when a{x}-{y}, baz{one}-{two}, and c all resolve, then finally resolve the whole expression.
I am shaky on my understanding of the logic flow for handling something like this, wondering if you could help solidify/clarify the general algorithm (high level pseudocode or something like that). Mainly just looking for how I would structure the data model and algorithm so as to progressively evaluate when the pieces are ready.
I'm starting out trying and it's not clear what to do next:
{
dependencies: [
{
path: [x]
},
{
path: [y]
}
],
parent: {
dependency: a{x}-{y} // interpolated term
parent: {
dependencies: [
{
}
]
}
}
}
Some sort of tree is probably necessary, but I am having trouble figuring out what it might look like, wondering if you could shed some light on that with some pseudocode (or JavaScript even).
watch the leaf nodes at first
then, when the children of a node are completed, propagate upward to resolving the next parent node. This would mean once x and y are done, it could resolve a{x}-{y}, but then wait until the other nodes are ready before doing the final top-level evaluation.
You can just simulate it by sending "events" to the system theoretically, like:
ready('y')
ready('c')
ready('x')
ready('a{x}-{y}')
function ready(variable) {
if ()
}
...actually that may not work, not sure how to handle the interpolated nodes in a hacky way like that. But even a high level description of how to solve this would be helpful.
export type SiteDependencyObserverParentType = {
observer: SiteDependencyObserverType
remaining: number
}
export type SiteDependencyObserverType = {
children: Array<SiteDependencyObserverType>
node: LinkNodeType
parent?: SiteDependencyObserverParentType
path: Array<string>
}
(What I'm currently thinking, some TypeScript)
Here is an approach in JavaScript:
Parse the input string to create a Node instance for each {} term, and create parent-child dependencies between the nodes.
Collect the leaf Nodes of this tree as the tree is being constructed: group these leaf nodes by their identifier. Note that the same identifier could occur multiple times in the input string, leading to multiple Nodes. If a variable x is resolved, then all Nodes with that name (the group) will be resolved.
Each node has a resolve method to set its final value
Each node has a notify method that any of its child nodes can call in order to notify it that the child has been resolved with a value. This may (or may not yet) lead to a cascading call of resolve.
In a demo, a timer is set up that at every tick will resolve a randomly picked variable to some number
I think that in your example, foo, and a might be functions that need to be called, but I didn't elaborate on that, and just considered them as literal text that does not need further treatment. It should not be difficult to extend the algorithm with such function-calling features.
class Node {
constructor(parent) {
this.source = ""; // The slice of the input string that maps to this node
this.texts = []; // Literal text that's not part of interpolation
this.children = []; // Node instances corresponding to interpolation
this.parent = parent; // Link to parent that should get notified when this node resolves
this.value = undefined; // Not yet resolved
}
isResolved() {
return this.value !== undefined;
}
resolve(value) {
if (this.isResolved()) return; // A node is not allowed to resolve twice: ignore
console.log(`Resolving "${this.source}" to "${value}"`);
this.value = value;
if (this.parent) this.parent.notify();
}
notify() {
// Check if all dependencies have been resolved
let value = "";
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
if (!child.isResolved()) { // Not ready yet
console.log(`"${this.source}" is getting notified, but not all dependecies are ready yet`);
return;
}
value += this.texts[i] + child.value;
}
console.log(`"${this.source}" is getting notified, and all dependecies are ready:`);
this.resolve(value + this.texts.at(-1));
}
}
function makeTree(s) {
const leaves = {}; // nodes keyed by atomic names (like "x" "y" in the example)
const tokens = s.split(/([{}])/);
let i = 0; // Index in s
function dfs(parent=null) {
const node = new Node(parent);
const start = i;
while (tokens.length) {
const token = tokens.shift();
i += token.length;
if (token == "}") break;
if (token == "{") {
node.children.push(dfs(node));
} else {
node.texts.push(token);
}
}
node.source = s.slice(start, i - (tokens.length ? 1 : 0));
if (node.children.length == 0) { // It's a leaf
const label = node.texts[0];
leaves[label] ??= []; // Define as empty array if not yet defined
leaves[label].push(node);
}
return node;
}
dfs();
return leaves;
}
// ------------------- DEMO --------------------
let s = "foo{a{x}-{y}}-{baz{one}-{two}}-foo{c}";
const leaves = makeTree(s);
// Create a random order in which to resolve the atomic variables:
function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
[array[j], array[i]] = [array[i], array[j]];
}
return array;
}
const names = shuffle(Object.keys(leaves));
// Use a timer to resolve the variables one by one in the given random order
let index = 0;
function resolveRandomVariable() {
if (index >= names.length) return; // all done
console.log("\n---------------- timer tick --------------");
const name = names[index++];
console.log(`Variable ${name} gets a value: "${index}". Calling resolve() on the connected node instance(s):`);
for (const node of leaves[name]) node.resolve(index);
setTimeout(resolveRandomVariable, 1000);
}
setTimeout(resolveRandomVariable, 1000);
your idea of building a dependency tree it's really likeable.
Anyway I tryed to find a solution as simplest possible.
Even if it already works, there are many optimizations possible, take this just as proof of concept.
The background idea it's produce a List of Strings which you can read in order where each element it's what you need to solve progressively. Each element might be mandatory to solve something that come next in the List, hence for the overall expression. Once you solved all the chunks you have all pieces to solve your original expression.
It's written in Java, I hope it's understandable.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class StackOverflow {
public static void main(String[] args) {
String exp = "foo{a{x}-{y}}-{baz{one}-{two}}-foo{c}";
List<String> chunks = expToChunks(exp);
//it just reverse the order of the list
Collections.reverse(chunks);
System.out.println(chunks);
//output -> [c, two, one, baz{one}-{two}, y, x, a{x}-{y}]
}
public static List<String> expToChunks(String exp) {
List<String> chunks = new ArrayList<>();
//this first piece just find the first inner open parenthesys and its relative close parenthesys
int begin = exp.indexOf("{") + 1;
int numberOfParenthesys = 1;
int end = -1;
for(int i = begin; i < exp.length(); i++) {
char c = exp.charAt(i);
if (c == '{') numberOfParenthesys ++;
if (c == '}') numberOfParenthesys --;
if (numberOfParenthesys == 0) {
end = i;
break;
}
}
//this if put an end to recursive calls
if(begin > 0 && begin < exp.length() && end > 0) {
//add the chunk to the final list
String substring = exp.substring(begin, end);
chunks.add(substring);
//remove from the starting expression the already considered chunk
String newExp = exp.replace("{" + substring + "}", "");
//recursive call for inner element on the chunk found
chunks.addAll(Objects.requireNonNull(expToChunks(substring)));
//calculate other chunks on the remained expression
chunks.addAll(Objects.requireNonNull(expToChunks(newExp)));
}
return chunks;
}
}
Some details on the code:
The following piece find the begin and the end index of the first outer chunk of expression. The background idea is: in a valid expression the number of open parenthesys must be equal to the number of closing parenthesys. The count of open(+1) and close(-1) parenthesys can't ever be negative.
So using that simple loop once I find the count of parenthesys to be 0, I also found the first chunk of the expression.
int begin = exp.indexOf("{") + 1;
int numberOfParenthesys = 1;
int end = -1;
for(int i = begin; i < exp.length(); i++) {
char c = exp.charAt(i);
if (c == '{') numberOfParenthesys ++;
if (c == '}') numberOfParenthesys --;
if (numberOfParenthesys == 0) {
end = i;
break;
}
}
The if condition provide validation on the begin and end indexes and stop the recursive call when no more chunks can be found on the remained expression.
if(begin > 0 && begin < exp.length() && end > 0) {
...
}

std::map find fails when key is pointer

I am unable to get the std::map find to locate the correct row in the std::map. The key is a class pointer and I have created a struct (tdEcApplDataMapEq) to compare the class's binary arrays for a match.'
The problem is it doesn't work. I call FoEcApplData::operator== when the find starts. It says the first entry does not a match and then the find returns out pointing to the first item on the std::map list. There is no attempt by find to search the other map entries. Also the one match test failed (false), so why is find saying its a match?
This probably has something to do with the std::map declaration. std::map says the third argument is for std::less, but I am doing a == vs. <.
If I change it to do < the same this happens. It enters FoEcApplData::operator< which return a true on the first check and find search stops with the search pointing to the 1st entry in the list.
How do I get find() to use the custom struct for the search?
My example adds 10 rows to FdTEcApplDataMap. It copies the CDH_DISABLE_XACT182 class into hold for the search later. I then do the find() test using hold as the search key.
Inside entry1
Inside entry2
Inside entry3<== this is the one I am searching for
Inside entry4
Inside entry5
Inside entry6
Inside entry7
Inside entry8
Inside entry9
Inside entry10
Inside entry1
This is the find:
auto hazard = ExcludedCmdDict.find(&hold);
if(hazard != ExcludedCmdDict.end())
{
std::cout << "found it " << hazard->second << std::endl;
}
This is the compare function being used:
bool FoEcApplData::operator==( const FoEcApplData& FoEcApplDataObject) const {
if(myNumOfBytes <= FoEcApplDataObject.NumOfBytes())
{
const EcTOctet* temp;
temp = FoEcApplDataObject.Data() ;
for(EcTInt i = 0; i < myNumOfBytes ; i++)
{
if(myData[i] != temp[i])
{
return false ;
}
}
return true;
}
else // myNumOfBytes > FoEcApplDataObject.NumOfBytes()
{
const EcTOctet* temp;
temp = FoEcApplDataObject.Data() ;
for(EcTInt i = 0; i < FoEcApplDataObject.NumOfBytes(); i++)
{
if(myData[i] != temp[i])
{
return false ;
}
}
return true;
}
}
This is the declaration for the std::map.
/*
Custom less for find on the FdTEcApplDataMap.
Needed since we are using pointers.
Returns - true - match, false - no match
node - pointer to the item you are looking for
node2 - pointer to an item on the list
*/
struct tdEcApplDataMapEq {
bool operator()(FoEcApplData *const& node, FoEcApplData *const& node2) const
{
return *node == *node2;
}
};
typedef std::map< FoEcApplData *, std::string, tdEcApplDataMapEq> FdTEcApplDataMap;
std::map expects the compare function to work like std::less. You need to use something along the lines of:
struct tdEcApplDataMapEq {
bool operator()(FoEcApplData *const& node, FoEcApplData *const& node2) const
{
return (*node < *node2); // Implement operator<() function for FoEcApplData
}
};
While at it, change the name of the struct to reflect the fact that it is trying to compute "less than".
struct tdEcApplDataMapLess {
bool operator()(FoEcApplData *const& node, FoEcApplData *const& node2) const
{
return (*node < *node2); // Implement operator<() function for FoEcApplData
}
};

C++: std::bind -> std::function

I have several functions which receive the following type:
function<double(int,int,array2D<vector<double *>>*)>
Where array2D is a custom type. Further, I have a function which takes the following as arguments:
double ising_step_distribution(double temp,int i,int j,array2D<vector<double *>>* model)
Right now, in order to bind the first value, temp, and return a functor which has the correct signature, I am writing:
double temp = some_value;
function<double(int,int,array2D<vector<double *>>*)> step_func =
[temp](int i, int j, array2D<vector<double *>>* model){
return ising_step_distribution(temp,i,j,model);
}
}
And this works. However, the following breaks:
auto step_func =
[temp](int i, int j, array2D<vector<double *>>* model){
return ising_step_distribution(temp,i,j,model);
}
}
With the following error:
candidate template ignored:
could not match
'function<double (int, int, array2D<vector<type-parameter-0-0 *, allocator<type-parameter-0-0 *> > > *)>'
against
'(lambda at /Users/cdonlan/home/mcmc/main.cpp:200:25)'
void mix_2D_model(function<double(int,int,array2D<vector<T*>>*)> step_distribution_func,...
And so, the code clump is ugly, obfuscative and repetitive (because I am making many of these).
I have been reading the documentation, and I understand that I should be able to write:
function<double(int,int,array2D<vector<double *>>*)> step_func =
bind(ising_step_distribution,temp,_1,_2,_3);
However, the only examples I have seen are for functions of type function<void()>. This one fails with an error:
// cannot cast a bind of type
// double(&)(double,int,int,array2D<vector<double *>>*)
// as function<double(int,int,...)
How do I get a visually clean bind and cast?
How do I get a visually clean bind and cast?
One way is:
using F = function<double(int,int,array2D<vector<double *>>*)>;
auto step_func =
[temp](int i, int j, array2D<vector<double *>>* model){
return ising_step_distribution(temp,i,j,model);
}
}
And then:
auto step_func_2 = F(step_func);
mix_2D_model(step_func_2, ...);
Or:
mix_2D_model(F(step_func), ...);

C++11 - Wrong constructor called in GCC/Clang (not in VS 2013)

I have this code which works fine in VS 2013 but doesn't compile in either GCC 4.8 or clang 3.3!
AND_end(c)->next = new ListNode<Point>{ b->val };
The error message is the following: "cannot convert from "Point" to "int".
Now, gradually, member val of b is a Point:
struct Point
{
int x;
int y;
double distance(const Point& other) const
{
if (this == &other)
return 0.;
return std::sqrt(std::pow(other.y - y, 2.) + std::pow(other.x - x, 2.));
}
bool operator==(const Point& other)
{
return x == other.x && y == other.y;
}
bool operator!=(const Point& other)
{
return !(*this == other);
}
};
b is a Line:
using Line = ListNode<Point>*;
a ListNode is a typical node for a singly linked list:
template<typename T>
struct ListNode
{
T val; // Value
ListNode* next = nullptr; // Next node in the list
// Constructor: takes a value of type T and optionally a pointer to the next node
explicit ListNode(T v, ListNode* n = nullptr)
: val{ v }, next{ n }
{
// Empty body, both member variables are initialized already
}
};
So, the line of code that doesn't compile should do the following: create a new ListNode, with T = Point, by supplying to the explicit ListNode constructor its first (and only) argument T v, which is a Point (b->val is a Point). This argument will be copied into the ListNode member val by copy, using the default copy constructor.
What seems to happen in both GCC and clang is that b->val is supplied to the Point constructor, hence the error message above (and for the sake of completeness, and additional warning is given: "missing field 'y' initializer").
VC++12 seems to get it all right instead.
So, what's up? Am I missing anything obvious (maybe, happens from time to time) or is there a nasty problem here?
I think the problem is, you do not have copy constructor for Point, therefore, in this line,
explicit ListNode(T v, ListNode* n = nullptr)
: val{ v }, next{ n }
since there's no copy constructor, val{v} will try to initialize by aggregate.
From 8.5.1,
An aggregate is an array or a class (Clause 9) with no user-provided
constructors.
When an aggregate is initialized by an initializer list,
as specified in 8.5.4, the elements of the initializer list are taken
as initializers for the members of the aggregate, in increasing
subscript or member order. Each member is copy-initialized from the
corresponding initializer-clause.
For a point type, the aggregate initialization shall be val {v.x, v.y}.
Or, you can implement a copy constructor for Point class.
GCC & Clang are correct. VS is wrong and it should reject your code.

how to sort a list in Vala using custom Comparator

I'm trying to get a directory listing and sort it into last modified time order using Vala.
I've got the directory listing part into a List < FileInfo >.
But I cannot figure out how to sort the list.
This is done via the the sort(CompareFunc<G> compare_func) method in the List class. You can read more about it here.
A basic example for strings would be:
list.sort((a,b) => {
return a.ascii_casecmp(b);
});
The return value of the function passed to sort() is the same as the ISO C90 qsort(3) function:
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
As you're interested in modify time, the FileAttribute you're looking for is TIME_MODIFIED which you would get by calling the appropriate get_attribute_* method of FileInfo.
static int main (string[] args) {
var directory = File.new_for_path ("/var/db/pkg");
var glib_list = new GLib.List<FileInfo> ();
try {
var enumerator = directory.enumerate_children (FileAttribute.TIME_MODIFIED, FileQueryInfoFlags.NOFOLLOW_SYMLINKS);
FileInfo file_info;
while ((file_info = enumerator.next_file()) != null) {
glib_list.append(file_info);
}
} catch(Error e) {
stderr.printf ("Error: %s\n", e.message);
}
// Lets sort it.
CompareFunc<FileInfo> my_compare_func = (a, b) => {
long c = a.get_modification_time().tv_sec;
long d = b.get_modification_time().tv_sec;
return (int) (c > d) - (int) (c < d);
};
glib_list.sort(my_compare_func);
foreach (FileInfo file_info in glib_list) {
stdout.printf ("%s\n", file_info.get_name());
}
return 0;
}

Resources