Created
June 3, 2013 04:23
-
-
Save stew/5696109 to your computer and use it in GitHub Desktop.
this is how I would have refactored
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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