Skip to content

Instantly share code, notes, and snippets.

@stew
Created June 3, 2013 04:23
Show Gist options
  • Select an option

  • Save stew/5696109 to your computer and use it in GitHub Desktop.

Select an option

Save stew/5696109 to your computer and use it in GitHub Desktop.
this is how I would have refactored
import scalaz.ValidationNel
import scalaz.syntax.traverse._
import scalaz.syntax.validation._
import scalaz.std.list._
sealed trait GetOptError
case object UnknownArgument extends GetOptError
case object EmptyElement extends GetOptError
private def parseArguments(i: Int, element: String): List[ValidationNel[GetOptError, (Char, Option[String])]] =
if(i == element.length) Nil else {
val c = element.charAt(i)
options_map.get(c) match {
// unknown argument, save that and keep looking for more errors
case None => UnknownArgument.failNel :: parseArguments(i+1, element)
// when we hit an opt with arguments, we grab the rest of the element as the argument
case Some(true) => List((c, Some(element.substring(i+1))).successNel)
// an opt without arguments, we recurse on the subsequent member of the string
case Some(false) => (c, None).successNel :: parseArguments(i+1, element)
}
}
private def validateElement(element: String): ValidationNel[GetOptError, String] =
if( element == "--" )
UnknownArgument.failNel
else if( element.length == 0 )
EmptyElement.failNel
else
element.successNel
private def parseElement(element:String):ValidationNel[GetOptError, Map[Char, Option[String]]] =
for {
valid <- validateElement(element)
args <- parseArguments(0, valid).sequenceU
} yield args.toMap
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment