Skip to content

Instantly share code, notes, and snippets.

@dholbrook
Created December 15, 2011 17:26
Show Gist options
  • Save dholbrook/1481965 to your computer and use it in GitHub Desktop.
Save dholbrook/1481965 to your computer and use it in GitHub Desktop.
S99 Problem 6
import scala.annotation.tailrec
object Palindrome extends App {
//don't want to use name "reverse" because of conflict with built-in
def rev[A](lst: List[A]): List[A] = {
@tailrec
def loop(rlst: List[A], accumulator: List[A]): List[A] = rlst match {
case Nil => accumulator
case head :: tail => loop(tail, head :: accumulator)
}
loop(lst, Nil)
}
//using custom reverse
def custPalindrome[A](l: List[A]): Boolean = rev(l) == l
//using built-ins
def palindroeme[A](l: List[A]): Boolean = l.reverse == l
val palList = List(1,2,3,2,1)
assert(custPalindrome(palList) == true)
assert(palindroeme(palList) == true)
//using pimp-my-library pattern
class CustPal(rl: List[Any]){
def palindrome = palindroeme(rl)
}
implicit def listToCustRev(l: List[Any]) = new CustPal(l)
assert(palList.palindrome)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment