Skip to content

Instantly share code, notes, and snippets.

@joescii
Last active April 6, 2016 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joescii/2d9f0f545eaa081c331563b67a4f6d26 to your computer and use it in GitHub Desktop.
Save joescii/2d9f0f545eaa081c331563b67a4f6d26 to your computer and use it in GitHub Desktop.
package com
import scala.annotation.tailrec
package object joescii {
@tailrec
def isPalindrome(s:String):Boolean =
if(s.length <= 1) true
else if(s.head == s.last) isPalindrome(s.drop(1).dropRight(1))
else false
}
package com.joescii
import org.scalacheck._
import Gen._
import Prop._
object PalindromeChecks extends Properties("palindrome") {
val randBoolean:Gen[Boolean] = for {
b <- choose(0,1)
} yield {
b == 0
}
val randPalindrome:Gen[String] = for {
s <- alphaStr
odd <- randBoolean
} yield {
if(s.length <= 1) s
else if(odd) s + s.reverse.drop(1)
else s + s.reverse
}
val randNonPalindrome:Gen[String] = for {
s <- alphaStr if s.length > 0
c <- alphaChar if s.head != c
} yield {
s + c
}
property("isPalindrome() should be true for all palindromes") = forAll(randPalindrome) { p =>
isPalindrome(p)
}
property("isPalindrome() should be false for all non-palindromes") = forAll(randNonPalindrome) { p =>
!isPalindrome(p)
}
}
@johanatan
Copy link

Should be able to use Arbitrary.arbBool rather than defining your own randBoolean.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment