1

我写了一个代码,它是关于 GLib.Tree 的。但不知道如何使用搜索方法。

Valadoc 有一个例子,并且有效!

下面是我的代码:

[indent = 4]

def cmp (a: string, b: string): int
    return strcmp (a, b)
init
    var t = new Tree of string, string (cmp)
    t.insert ("a", "aaa")
    t.insert ("b", "bbb")

    var needle = "A"
    fun: TreeSearchFunc = def (k)
        return strcmp (k.down(), needle.down())

    var ret = t.search (fun)

错误!

错误:名称down' does not exist in the context ofK'

再试一次:

    fun: TreeSearchFunc of string = def (k)

错误!

错误:“GTreeSearchFunc”未声明

TreeSearchFunc 说明:

public delegate int TreeSearchFunc (K key) 

如果我想写一个 TreeSearchFunc 委托?怎么做?

4

1 回答 1

0

从实际的角度来看,您正在为 GLib.Tree 实现不区分大小写的搜索。使用该search_key()功能可能会更好:

[indent = 4]
init
    var tree = new Tree of ( string, string )( cmp )
    tree.insert( "a", "aaa" )
    tree.insert( "b", "bbb" )

    result:string = tree.search_key( case_insensitive_compare, "A" )
    print result

def cmp( a:string, b:string ):int
    return strcmp( a, b )

def case_insensitive_compare ( a:string, b:string ):int
    return strcmp( a.down(), b.down() )

由于您的问题特别要求TreeSearchFunc委托,那么代码将是:

[indent = 4]
init
    var tree = new Tree of ( string, string ).full( cmp, free, free )
    tree.insert( "a", "aaa" )
    tree.insert( "b", "bbb" )

    result:string = tree.search( case_insensitive_search_for_a )
    print result

def cmp( a:string, b:string ):int
    return strcmp( a, b )

def case_insensitive_search_for_a ( k:string ):int
    return strcmp( k.down(), "A".down() )

需要注意的几点:

  • 委托版本必须在TreeSearchFunc其范围内包含搜索词“A”。Valadoc 中的示例使用了一个闭包,它还包括封闭范围,不幸的是你还不能在 Genie 中这样做
  • 使用的 Valadoc 版本Tree.full,所以我在TreeSearchFunc委托版本中展示了如何做到这一点。这是在您不确定如何在 Genie 中使用类型参数(泛型)的情况下

在您的示例中,您正确地尝试通过将其分配给变量来在 Genie 中使用闭包。这仅在 Vala 的开发版本中可用,因此您必须下载并编译最新的 Vala。这应该在 Vala 0.32 发布时可用。如果您尝试在 Vala 中使用相同的方法,您将得到相同的错误。所以我认为问题出在 Vala 编译器上。目前 Genie 不支持在括号或大括号内定义匿名函数。如果您有兴趣添加支持,请查看https://bugzilla.gnome.org/show_bug.cgi?id=760492

于 2016-01-11T20:54:36.183 回答