I am trying to write a tail recursion function to reverse string, here is the code, some reason I am not sure if the pattern match condition is preventing it from getting the reversed string as output
def revstring(str:String):String={
@tailrec
def rev(str:String,r:String):String={
str match{
case s if s.head==null =>null
case x if x.tail.isEmpty => ""
case _=> rev(str.tail, str.head +r)
}
}
rev(str,"")}println(revstring("Mississipi"))
}
s.head
is never null. It'll throw an exception if the string is empty (or if it is null, which it should never be - nulls should never really appear in scala code).
Also, you are returning too early - x.tail.isEmpty
means you still have one char remaining to process.
Finally, you always return ""
instead of the actual result.
Something like this should work:
str match {
case "" => r
case s => rev(s.tail, s.head + r)
}
As mentioned in the comment, manipulating strings like this isn't very performant. So, in real life you'd probably want to convert it into a list, reverse the list, and then .mkstring
to put it back together.