Skip to content

Instantly share code, notes, and snippets.

@vdichev
vdichev / scala-exercises.scala
Created June 17, 2017 06:46
Scala exercises
Exercises
=========
Scala intro
-----------
1. Check if a string has balanced parentheses.
2. There is an inventory of items in a shop costing 615, 452, 356, 184, 172, 156, 135, 115, 78, 56, 48 lv. Find at least one way to spend exactly 992 lv. How about exactly 796 lv.?
@vdichev
vdichev / gist:1510309
Created December 22, 2011 13:27
PartialFunction challenge
// Let's say I have 2 or more partial functions with different argument types
// I'm not interested in the result or the result types here
trait Test[A] { val pf: PartialFunction[A,_] }
object TestInt extends Test[Int] { val pf: PartialFunction[Int,String] = { case i => i.toString } }
object TestString extends Test[String] { val pf: PartialFunction[String,Int] = { case s => s.toInt } }
// I want to be able to chain these with orElse:
val pf = TestInt.pf orElse TestString.pf
// ...except that this doesn't work: neither pf.isDefinedAt(1) nor pf.isDefinedAt("str") work
email := userList?.findUser("bob")?.email
post("/statuses/update.xml", "status" -> "test_msg1")
\\(<text>test_msg1</text>)
\\(<screen_name>vdichev</screen_name>)
get("/statuses/public_timeline.xml") \\(<text>test_msg1</text>)
get("/statuses/user_timeline.xml") \\(<text>test_msg1</text>)
get("/statuses/home_timeline.xml") \\(<text>test_msg1</text>)
for {
message <- post("/statuses/update.xml", "status" -> "test_msg1")
!@ "Couldn't post message" if message.xml must notBeEmpty
xml <- message.xml
} {
xml must \\(<text>test_msg1</text>)
}
trait XmlResponse {
self: TestResponse =>
def xmlMatch(f: Elem => Unit)
(implicit errorFunc: ReportFailure): TestResponse = {
if (this.asInstanceOf[SelfType].code != 200)
errorFunc.fail("Response status is not 200!")
xml match {
case Full(xml) => f(xml); this
case _ => errorFunc.fail("Response contains no XML!")
}
override def theHttpClient = {
val theClient = buildBasicAuthClient(userName, password)
theClient.getParams.setAuthenticationPreemptive(true)
theClient
}
get("/account/verify_credentials.xml")
! (401, "Login should fail with Unauthorized status")
for {
login <- get("/account/verify_credentials.xml", httpClient, Nil)
!@ "Failed to log in"
message <- login.post("/statuses/update.xml", "status" -> "test_msg1")
!@ "Couldn't post message"
xml <- message.xml
} {
// Specs' xml matcher
xml must \\(<text>test_msg1</text>)
}
implicit val reportError = new ReportFailure {
def fail(msg: String): Nothing = TwitterAPISpecs.this.fail(msg)
}