Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Usign Applicatives to replace ':value' placeholders in a string
- // All errors are accumulated into a ValidationNEL
- sealed trait ParamsReplacer {
- val str: String
- private val r = ":([a-zA-Z0-9]+)".r
- private def f(p:Params) = (m:Match) => {
- val s = m.toString.drop(1)
- (p get s).toSuccess(s"Param '$s' is required").toValidationNEL
- }
- def replace(params: Params) = {
- val reduce = (a: String, b: (Match, String)) => b._1.matched.r.replaceFirstIn(a, b._2)
- val zipAndReduce = (a:List[Match], b:List[String]) => (a zip b).foldLeft(str)(reduce)
- val matchList = r.findAllMatchIn(str).toList
- (matchList.successNel[String] |@|
- (matchList <*> f(params).pure[List]).sequenceU)(zipAndReduce)
- }
- }
- object ParamsReplacer {
- def apply(s: String):ParamsReplacer = new ParamsReplacer {
- val str = s
- }
- }
- // Use:
- scala> val rep = ParamsReplacer("retweets_of_me.:format.:test")
- rep: com.logikujo.Spore.ParamsReplacer = com.logikujo.Spore.ParamsReplacer$$anon$1@7ce9a760
- // Scary type :) The cool part is the Failure(NonEmptyList(Error1, Error2))
- scala> rep.replace(Map.empty)
- res1: scalaz.Unapply[scalaz.Apply,scalaz.ValidationNEL[String,List[scala.util.matching.Regex.Match]]]{type M[X] = scalaz.ValidationNEL[String,X]; type A = List[scala.util.matching.Regex.Match]}#M[String] = Failure(NonEmptyList(Param 'format' is required, Param 'test' is required)
- scala> rep.replace(Map("format" -> "json"))
- res3: scalaz.Unapply[scalaz.Apply,scalaz.ValidationNEL[String,List[scala.util.matching.Regex.Match]]]{type M[X] = scalaz.ValidationNEL[String,X]; type A = List[scala.util.matching.Regex.Match]}#M[String] = Failure(NonEmptyList(Param 'test' is required))
- // A Success! :)
- scala> rep.replace(Map("format" -> "json", "test" -> "JustATest"))
- res4: scalaz.Unapply[scalaz.Apply,scalaz.ValidationNEL[String,List[scala.util.matching.Regex.Match]]]{type M[X] = scalaz.ValidationNEL[String,X]; type A = List[scala.util.matching.Regex.Match]}#M[String] = Success(retweets_of_me.json.JustATest)
Advertisement
Add Comment
Please, Sign In to add comment