簡體   English   中英

F#中的不可變Trie結構

[英]Immutable Trie structure in F#

我正在使用aho-corasick算法來嘗試使用F#更好一點,我遇到了Trie實現的問題,它們都是可變的或者不能進行尾調用優化。

我可以看到的基本問題是,不可變數據結構必須“自下而上”構建,因為你不能改變他們所指向的內容,所以你的選擇要么讓它們變得可變,要么在你去的時候找出節點(即在施工中遞歸)。

有沒有辦法在構造上使用尾調用優化來創建一個不可變的trie數據結構?(而不是通過復制來降低效率)。

可以通過使用延續來消除尾調用優化。 這是一個示例,其中鍵和值分別是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)

如果你想堅持使用不可變結構,消除副本會有點困難

我在研究我的代碼審查帖子時發現了這篇文章,我在不可變的trie中實現了這個帖子。

使用映射表示鏈接而不是二叉樹是高性能的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM