Skip to content

Instantly share code, notes, and snippets.

View imeredith's full-sized avatar

Ivan Meredith imeredith

View GitHub Profile
trait PartialType[T[_, _], A] {
type Apply[B] = T[A, B]
type Flip[B] = T[B, A]
}
trait Fluffy[F[_]] {
def furry[A, B](f: A => B, fa: F[A]): F[B]
}
object Fluffy {
val validTask = (json \ "taskId").asOpt[String] match {
case Some(taskId) if taskId.contains("UNUSED_") => new Exception("Ignoring %s, its unused event and not supposed to be billed.").fail[String]
case Some(taskId) if !taskId.isEmpty => taskId.success[Throwable]
case _ => new Exception("taskId does not exist").fail[String]
}
@imeredith
imeredith / Applicative.scala
Created July 28, 2012 03:25 — forked from tonymorris/Applicative.scala
Applicative exercise
object Applicative {
// pick any monad, I have picked Option for you
type F[A] = Option[A]
// Applicative primitive given concrete
// AKA point, pure, return
def lift0[A](a: A): F[A] =
Some(a)
// Applicative primitive given concrete
scala> val x = implicitly[Monoid[Promise]]
<console>:7: error: not found: type Monoid
val x = implicitly[Monoid[Promise]]
^
<console>:7: error: ambiguous implicit values:
both method stringCanBuildFrom in object Predef of type => scala.collection.generic.CanBuildFrom[String,Char,String]
and method conforms in object Predef of type [A]=> <:<[A,A]
match expected type <error>
val x = implicitly[Monoid[Promise]]
^
for{
header <- Option(req.getHeader("Authorization"))
base64 <- Option(header.substring(0,6)) if base64.equals("Basic ")
encoded <- Option(header.substring(6))
auth <- Option(new String(new Base64().decode(encoded.getBytes))) if auth == "%s:%s".format(Config.basicUser, Config.basicPassword)
} yield auth
if(auth.isEmpty) {
resp.setHeader("WWW-Authenticate", "Basic Realm=\"cloudbees\"")
resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED)
case class SomeModel(field1: String, field2)
def js[A:Reads](field: String)(implicit request: Request[JsValue]): Option[A] = (request.body \ field).asOpt[A]
def index = Action(parse.json) { implicit request =>
val field1 = js[String]("field1")
val field2 = js[String]("field2")
if(!field1.isDefined){
BadRequest(Json.toJson(Map("error" -> "Field 'field1' is not defined")))
case class SomeModel(field1: String, field2: String)
def index = Action(parse.json) { implicit request =>
val validation = for {
field1 <- js[String]("field1")
field2 <- js[String]("field2")
} yield (field1 |@| field2)(SomeModel.apply)
validation(request.body).fold(
e => BadRequest(Json.toJson(Map("errors" -> Json.toJson(e.toList)))),
1
1 1
1 2 1
1 3 6 3 1
for {
a <- list.headOption
b <- doSomething(a)
c <- doSomethingElse(b)
} yield c
for {
a <- Option("stuff")
b <- doStuff(a)
c <- doMoreStuff(b)
} yield c