【问题标题】:Immutable Trie structure in F#F# 中的不可变 Trie 结构
【发布时间】:2011-03-22 18:08:19
【问题描述】:

我正在使用 aho-corasick 算法来尝试让 F# 变得更好一些,但我遇到了 Trie 实现的问题,它们都是可变的或者不能进行尾调用优化。

我所看到的基本问题是,不可变数据结构必须“自下而上”构建,因为您无法更改它们指向的内容,因此您的选择是使它们可变,或者找出节点为你继续(即在构造中递归)。

有什么方法可以在构造上通过尾调用优化来制作不可变的 trie 数据结构?(并且不会因复制而降低效率。)

【问题讨论】:

    标签: f# immutability trie tail-call


    【解决方案1】:

    尾调用优化可以通过使用延续来消除。这是一个示例,其中键和值分别为stringint

    type Trie = 
     | Data of string * int * Trie * Trie 
     | Leaf 
    
    let Insert start key value = 
      let rec inner current withNode = 
        match current with
        | Data (currentKey, currentValue, left, right) ->
          if key < currentKey then
            inner left (fun left -> Data (currentKey, currentValue, left, right))
          else 
            inner right (fun right -> Data (currentKey, currentValue, left, right))
        | Leaf -> withNode (Data (key, value, Leaf, Leaf))
      inner start (fun x -> x)
    

    如果你想坚持不可变结构,消除副本会有点困难

    【讨论】:

    • 啊,续篇,我发现这些让我头疼,所以我想熟能生巧,谢谢。甚至可以消除复制吗?看到你在这里是如何做到的,我意识到这并没有我想象的那么重要(复制的数据比我想象的要少)但是以原则等名义。我很好奇。
    • @user442859 是的,延续需要一段时间才能习惯。我认为这是一项个人成就,我能够只用一个小的语法错误就完成了这个。我确信在许多情况下有一种方法可以消除这种应对方式,但我个人不知道对于这种树结构有什么好的方法
    【解决方案2】:

    我在研究 my code review post 时遇到了这篇文章,我在 immutable trie 上实现了该帖子。

    使用地图作为链接而不是二叉树是高效的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多