[Vala] Sorting an ArrayList of objects by a specific property



I'm attempting to sort an ArrayList of a certain type of object, but with
my current code (below) I keep getting the error: "The name `dist' does not
exist in the context of `DistValue'"

Any advice on how to do this?

Alternatively, my end goal is that I'm calculating the distance between
several nodes using cosine similarity for a k nearest neighbor algorithm,
and I need a method of storing associated values of <string, double> and
then returning the strings associated with the k greatest values.  My
method of doing this in Python is to create a dictionary (i.e. HashMap) to
store the string, value associations while working with them, and then
convert this into a list sorted by the values, but I'm not sure how I would
do such a thing in Vala (hence the attempt with objects to do the same).

Thanks for the assist!
Ryan Smith

using Gee;

public class DistValue : GLib.Object {
    public double dist;
    public string instanceID;

    public DistValue (string instanceID, double dist) {
        this.dist = dist;
        this.instanceID = instanceID;
    }
}

public int CompareDistValue<DistValue> (DistValue a, DistValue b) {
    if (a.dist > b.dist)
    {return 1;}
    if (a.dist == b.dist)
    {return 0;}
    return -1;
}

void main() {
    var simils = new ArrayList <DistValue> ();

    var distB = new DistValue ("b", 3.0);
    var distA = new DistValue ("a", 5.0);

    simils.add(distB);
    simils.add(distA);

    simils.sort (CompareDistValue);

    foreach (var item in simils) {
        stdout.printf("%s: %s\n", item.instanceID, item.dist.to_string ());
    }
}


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]