gpt4 book ai didi

haskell - Haskell 中的 Knuth-Morris-Pratt 算法

转载 作者:行者123 更新时间:2023-12-04 02:21:25 30 4
gpt4 key购买 nike

我很难理解 Haskell 中 Knuth-Morris-Pratt 算法的这种实现。

http://twanvl.nl/blog/haskell/Knuth-Morris-Pratt-in-Haskell

特别是我不了解自动机的构造。我知道它使用“Tying the Knot”方法来构建它,但我不清楚,我也不知道为什么它应该具有正确的复杂性。

我想知道的另一件事是你是否认为这个实现可以很容易地推广到实现 Aho-Corasick 算法。

感谢您的回答!

最佳答案

所以这里的算法:

makeTable :: Eq a => [a] -> KMP a
makeTable xs = table
where table = makeTable' xs (const table)

makeTable' [] failure = KMP True failure
makeTable' (x:xs) failure = KMP False test
where test c = if c == x then success else failure c
success = makeTable' xs (next (failure x))

使用它,让我们看看为“shoeshop”构建的表:
makeTable "shoeshop" = table0

table0 = makeTable' "shoeshop" (const table0)
= KMP False test0

test0 c = if c == 's' then success1 else const table0 c
= if c == 's' then success1 else table0

success1 = makeTable' "hoeshop" (next (const table0 's'))
= makeTable' "hoeshop" (next table0)
= makeTable' "hoeshop" test0
= KMP False test1

test1 c = if c == 'h' then success2 else test0 c

success2 = makeTable' "oeshop" (next (test0 'h'))
= makeTable' "oeshop" (next table0)
= makeTable' "oeshop" test0
= makeTable' "oeshop" test0
= KMP False test2

test2 c = if c == 'o' then success3 else test0 c

success3 = makeTable' "eshop" (next (test0 'o'))
= makeTable' "eshop" (next table0)
= makeTable' "eshop" test0
= KMP False test3

test3 c = if c == 'e' then success4 else test0 c

success4 = makeTable' "shop" (next (test0 'e'))
= makeTable' "shop" (next table0)
= makeTable' "shop" test0
= KMP False test4

test4 c = if c == 's' then success5 else test0 c

success5 = makeTable' "hop" (next (test0 's'))
= makeTable' "hop" (next success1)
= makeTable' "hop" test1
= KMP False test5

test5 c = if c == 'h' then success6 else test1 c

success6 = makeTable' "op" (next (test1 'h'))
= makeTable' "op" (next success2)
= makeTable' "op" test2
= KMP False test6

test6 c = if c == 'o' then success7 else test2 c

success7 = makeTable' "p" (next (test2 'o'))
= makeTable' "p" (next success3)
= makeTable' "p" test3
= KMP False test7

test7 c = if c == 'p' then success8 else test3 c

success8 = makeTable' "" (next (test3 'p'))
= makeTable' "" (next (test0 'p'))
= makeTable' "" (next table0)
= makeTable' "" test0
= KMP True test0

注意 success5使用消耗的“s”来回溯模式的初始“s”。

现在来看看当你做 isSubstringOf2 "shoeshop" $ cycle "shoe" 时会发生什么。 .

test7匹配 'p' 失败,它回退到 test3尝试匹配'e',这样我们就循环通过 success4 , success5 , success6success7无止境。

关于haskell - Haskell 中的 Knuth-Morris-Pratt 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16694306/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com