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 - Юн Вадим #274

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
36 changes: 36 additions & 0 deletions homeworks/homework_8/src/main/scala/Exercises.scala
Original file line number Diff line number Diff line change
@@ -1,3 +1,39 @@
import scala.util.Try
import scala.util.matching.Regex

object Exercises {

val regSome = new Regex("""Some\((\S+)\)""")

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

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

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

implicit object readString extends Read[String] {
def read(str: String): Either[String, String] = Right(str)
}

implicit object readInt extends Read[Int] {
def read(str: String): Either[String, Int] = Try(str.toInt).toOption match {
case Some(value) => Right(value)
case None => Left("failed to parse")
}
}

implicit def readOption[T: Read]: Read[Option[T]] = {
case regSome(value) => value.read[T] match {
case Right(value) => Right(Some(value))
case Left(_) => Left("failed to read option")
}
case "None" => Right(None)
case _ => Left("Unexpected")
}
}
}