F#中的不可变Trie结构

Sna*_*ark 6 f# immutability trie tail-call

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

我可以看到的基本问题是,不可变数据结构必须"自下而上"构建,因为你不能改变他们所指向的内容,所以你的选择要么让它们变得可变,要么在你去的时候找出节点(即在施工中递归).

有没有办法在构造上使用尾调用优化来创建一个不可变的trie数据结构?(而不是通过复制来降低效率).

Jar*_*Par 8

可以通过使用延续来消除尾调用优化.下面是一个示例,其中键和值是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)
Run Code Online (Sandbox Code Playgroud)

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