Tuesday, April 30, 2019

isPalindrome Implementation in Scala

The palindrome function will check the Given Number/ String is Palindrome or In case of List of Items It will test individual items in list can contribute to a Palindrome or Not.

def isPalindrome[A](item:A):Boolean = item match {
  case head :: Nil => isPalindrome(head)
  case ls:List[A] => ls.head == ls.last &&  isPalindrome(ls.drop(1).dropRight(1))// Checks the Head and Tail, and recursively check for the remaining
  case ls:String => ls.reverse == ls
  case e => e.toString.reverse == e.toString
}

println("IS Palindrome :"+isPalindrome(1234454321))  // Result false
println("IS Palindrome :"+isPalindrome(List(1,2,3,4,3,2,1)))  // Result true
println("IS Palindrome :"+isPalindrome("ABCDCBA"))  // Result true

No comments: