Scala 尾部递归Knuth–;莫里斯&x2013;普拉特算法
我已经在Scala中创建了一个简单的实现。现在,我想想象一下,用递归的方式做同样的事情。我的直觉告诉我,这应该不会太难(无论是表格还是搜索部分),但同样的感觉也告诉我,这一定是由比我更聪明的人完成的。这就是问题所在。你知道Knuth–Morris–Pratt算法的任何尾部递归实现吗Scala 尾部递归Knuth–;莫里斯&x2013;普拉特算法,scala,tail-recursion,knuth-morris-pratt,Scala,Tail Recursion,Knuth Morris Pratt,我已经在Scala中创建了一个简单的实现。现在,我想想象一下,用递归的方式做同样的事情。我的直觉告诉我,这应该不会太难(无论是表格还是搜索部分),但同样的感觉也告诉我,这一定是由比我更聪明的人完成的。这就是问题所在。你知道Knuth–Morris–Pratt算法的任何尾部递归实现吗 object KnuthMorrisPrattAlgorithm { def search(s: String, w: String): Int = { if (w.isEmpty) { re
object KnuthMorrisPrattAlgorithm {
def search(s: String, w: String): Int = {
if (w.isEmpty) {
return 0
}
var m = 0
var i = 0
val t = table(w)
while(m + i < s.length) {
if (w(i) == s(m + i)) {
if (i == w.length - 1) {
return m
}
i += 1
} else {
if (t(i) > -1) {
i = t(i)
m += i - t(i)
} else {
i = 0
m += 1
}
}
}
return -1
}
def table(w: String): Seq[Int] = {
var pos = 2
var cnd = 0
val t = Array(-1, 0) ++ Array.fill(w.size - 2)(0)
while (pos < w.length) {
if (w(pos - 1) == w(cnd)) {
cnd += 1
t(pos) = cnd
pos += 1
} else if (cnd > 0) {
cnd = t(cnd)
} else {
t(pos) = 0
pos += 1
}
}
t
}
}
对象knuthmorrispratt算法{
def搜索(s:String,w:String):Int={
如果(w.isEmpty){
返回0
}
var m=0
变量i=0
val t=表(w)
而(m+i-1){
i=t(i)
m+=i-t(i)
}否则{
i=0
m+=1
}
}
}
返回-1
}
def表(w:String):Seq[Int]={
var pos=2
var cnd=0
valt=Array(-1,0)+Array.fill(w.size-2)(0)
而(位置0){
cnd=t(cnd)
}否则{
t(pos)=0
pos+=1
}
}
T
}
}
我不知道该算法的作用,但这里是您的函数,尾部递归:
object KnuthMorrisPrattAlgorithm {
def search(s: String, w: String): Int = {
if (w.isEmpty) {
return 0
}
val t = table(w)
def f(m: Int, i: Int): Int = {
if (m + i < s.length) {
if (w(i) == s(m + i)) {
if (i == w.length - 1) {
m
} else {
f(m, i + 1)
}
} else {
if (t(i) > -1) {
f(m + i - t(i), t(i))
} else {
f(m + 1, 0)
}
}
} else {
-1
}
}
f(0, 0)
}
def table(w: String): Seq[Int] = {
val t = Array(-1, 0) ++ Array.fill(w.size - 2)(0)
def f(pos: Int, cnd: Int): Array[Int] = {
if (pos < w.length) {
if (w(pos - 1) == w(cnd)) {
t(pos) = cnd + 1
f(pos + 1, cnd + 1)
} else if (cnd > 0) {
f(pos, t(cnd))
} else {
t(pos) = 0
f(pos + 1, cnd)
}
} else {
t
}
}
f(2, 0)
}
}
对象knuthmorrispratt算法{
def搜索(s:String,w:String):Int={
如果(w.isEmpty){
返回0
}
val t=表(w)
def(m:Int,i:Int):Int={
如果(m+i-1){
f(m+i-t(i),t(i))
}否则{
f(m+1,0)
}
}
}否则{
-1
}
}
f(0,0)
}
def表(w:String):Seq[Int]={
valt=Array(-1,0)+Array.fill(w.size-2)(0)
def f(位置:Int,cnd:Int):数组[Int]={
如果(位置0){
f(职位,t(cnd))
}否则{
t(pos)=0
f(位置+1,cnd)
}
}否则{
T
}
}
f(2,0)
}
}
谢谢。今天晚些时候,我将更深入地研究它并运行一些测试。顺便问一下,你是如何做到这一点的,而不知道基本的算法?是否有任何技术可以机械地将循环转换为尾部递归函数?尾部递归是指使用参数来表示执行状态。我将局部变量参数设置为tail递归函数,然后我没有更改变量,而是将它们的新值递归地传递给函数。编译器抱怨第二个例子中关于t的行cnd=t(cnd)
@ViliusNormantas,是的,我实际上抛出了它。它并不比原来的版本好多少:我已经在内部函数中添加了@tailrec,编译器也没有抱怨。