【问题标题】:Genie's GLib TreeSearchFunc delegateGenie 的 GLib TreeSearchFunc 委托
【发布时间】:2016-01-11 08:34:03
【问题描述】:

我写了一个代码,它是关于 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 委托? 该怎么做?

【问题讨论】:

    标签: delegates genie


    【解决方案1】:

    从实际的角度来看,您正在为 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

    【讨论】:

    • 我想问另一个关于如何使用Tree.full的问题,但你已经给了我答案!我以前从未见过这种语法。 “新的 A of (B, C).D (E)” 谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-01-12
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 2023-04-11
    相关资源
    最近更新 更多