Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

homework_8 - Бусыгин Никита #198

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion homeworks/homework_8/project/build.properties
Original file line number Diff line number Diff line change
@@ -1 +1 @@
sbt.version = 1.3.3
sbt.version = 1.6.2
33 changes: 32 additions & 1 deletion homeworks/homework_8/src/main/scala/Exercises.scala
Original file line number Diff line number Diff line change
@@ -1,3 +1,34 @@
import scala.util.Try
import scala.util.{Success, Try, Failure}
import scala.util.matching.Regex

object Exercises {
trait Read[T] {
def read(str: String): Either[String, T]
}

object Read {
def read[T](str: String)(implicit read: Read[T]): Either[String, T] = read.read(str)
}

implicit class ReadOps(str: String) {
def read[T](implicit read: Read[T]): Either[String, T] = read.read(str)
}

implicit def stringRead: Read[String] = (str: String) => Right(str)

implicit def intRead: Read[Int] = (str: String) => Try(str.toInt) match {
case Success(value) => Right(value)
case Failure(_) => Left("Failed to read a number")
}

implicit def optionRead[T: Read]: Read[Option[T]] = {
case "None" => Right(None)
case str => """Some\((.+)\)""".r.findFirstMatchIn(str) match {
case Some(opt) => Read.read[T](opt.group(1)) match {
case Right(value) => Right(Some(value))
case Left(_) => Left("Failed to read option value")
}
case None => Left("Incorrect format")
}
}
}