Studying the Functional Programming book by Manning and struggling a bit. Doesn't the below hasSubsequence fail because the first time it encounters the first startsWith(sup, sub)
returning false the whole function hasSubSequence
returns false
at that point and it does not check the subsequent letters?
@annotation.tailrec
def startsWith[A](l: List[A], prefix: List[A]): Boolean = (l,prefix) match {
case (_,Nil) => true
case (Cons(h,t),Cons(h2,t2)) if h == h2 => startsWith(t, t2)
case _ => false
}
@annotation.tailrec
def hasSubsequence[A](sup: List[A], sub: List[A]): Boolean = sup match {
case Nil => sub == Nil
case _ => startsWith(sup, sub)
case Cons(h,t) => hasSubsequence(t, sub)
}
Aucun commentaire:
Enregistrer un commentaire