Haxe,ListSort.sort()问题

问题描述 投票:2回答:2
var persons: List<Person> = readPersonsFile("persons.txt");
ListSort.sort(persons, function(personA, personB): Int
{
    return Person.compare(personA.first(), personB.first());
});

我只是想对这份清单进行排序。它给了我这个错误:

Constraint check failure for sort.T
List<Person> should be { prev : List<Person>, next : List<Person> }
List<Person> has no field next

这对我来说很奇怪,因为它听起来像是想让我传递一个带有两个不同列表的隐含对象,如果真的是这样的话...如果那是真的那就不是很绝对。

haxe
2个回答
1
投票

ListSort只是单独或双重链接列表上的supposed to work; List类既不是这些类(虽然它与它们共享一些API,但具有不同的时间和空间成本)。

在你的情况下,你可以改变readPersonsFile返回Arrayhaxe.ds.GenericStack,并使用persons.sort(cmp)ListSort.sortSingleLinked(persons.head, cmp)

此外,如果有必要,您可以轻松地将任何可迭代 - 即具有iterator:Void->Iterator<T>方法的任何对象 - 转换为带有Lambda.array(iterable)的数组。


documentation缺乏对T参数的必要约束。这是文档生成器中的一个错误,我将尽快报告。


0
投票

从我可以看到haxe.ds.ListSort应该工作在链接列表类似的结构,而不是Haxe列表。如果您只想对列表进行排序,则可能更容易使用Array。如果您的目标是使用这种特定类型的排序并希望避免使用数组(例如,由于内存限制),您只需要为其提供如下结构:

typedef PersonListItem = {
    var prev:PersonListItem;
    var next:PersonListItem;
    var person:Person;
}

(实际上是Haxe List内部使用的ListItem

但我想你只想排序“一个列表”。所以,如果这就是你的意思,它可能看起来像这样:

class Test {
    static function main() {
        var persons:Array<Person> = readPersonsFile("persons.txt");
        trace(persons.join(","));
        persons.sort(Person.compare);
        trace(persons.join(","));
        trace(persons[0]);
    }

    static function readPersonsFile(name:String):Array<Person> {
        var result = new Array<Person>();
        result.push(new Person(8));
        result.push(new Person(1));
        result.push(new Person(2));
        result.push(new Person(6));
        result.push(new Person(0));
        result.push(new Person(9));
        result.push(new Person(3));
        result.push(new Person(7));
        result.push(new Person(4));
        result.push(new Person(5));
        return result;
    }
}

class Person {
    var id:Int;

    public function new(id) {
        this.id = id;
    }

    public static function compare(a:Person, b:Person):Int {
        return a.id - b.id;
    }

    public function toString():String {
        return 'Person($id)';
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.