Created
December 15, 2011 17:26
-
-
Save dholbrook/1481965 to your computer and use it in GitHub Desktop.
S99 Problem 6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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