F# 中的不可变 Trie 结构

发布于 2024-10-26 11:10:23 字数 233 浏览 4 评论 0原文

我正在尝试使用 aho-corasick 算法来尝试使用 F# 来改进一点,并且我遇到了 Trie 实现的问题,它们都是可变的或者无法进行尾部调用优化。

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

有没有办法制作一个不可变的 trie 数据结构,并在构造上进行尾调用优化?(并且不会因复制而损失效率。)

I am playing around with the aho-corasick algorithm to try and get a little better with F#, and I ran across a problem with the Trie implementations, they are all mutable or can't be tail call optimized.

The basic issue from what I can see is that immutable data structures have to be built "bottom up" since you can't change what they point to, so your options are either make them mutable, or find out the nodes as you go along(i.e. recurse in construction).

Is there any way of making an immutable trie data structure with tail call optimizations on the construction?(and not lose efficiency by copying.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一腔孤↑勇 2024-11-02 11:10:23

尾部调用优化可以通过使用延续来消除。这是一个示例,其中键和值分别为 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)

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

The tail call optimiation can be eliminated by using a continuation. Here's a sample where the key and value are string and int respectively

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)

Eliminating the copies is a bit more difficult if you want to stick with immutable structures

岁吢 2024-11-02 11:10:23

我在研究我的代码审查帖子时发现了这篇文章,我在其中实现了不可变的特里树。

它使用链接映射而不是二叉树来提高性能。

I came across this post while researching for my code review post where I've implemented at immutable trie.

It is performant using maps for links rather than binary trees.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文