-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMain.scala
64 lines (46 loc) · 1.65 KB
/
Main.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package example
import cats.effect.IO
import com.github.battermann.pureapp._
import cats.implicits._
import com.github.battermann.pureapp.interpreters.{FileSystem, Terminal}
object Main extends StandardPureApp[IO] {
// MODEL
type Model = Option[Either[String, String]]
sealed trait Msg
final case class ReadFromFile(fileName: String) extends Msg
final case class FileContentResult(result: Either[Throwable, String])
extends Msg
case object Quit extends Msg
sealed trait Cmd
object Cmd {
case object Empty extends Cmd
final case class ReadFromFile(fileName: String) extends Cmd
}
def init: (Model, Cmd) = (None, Cmd.Empty)
def quit(msg: Msg): Boolean = msg == Quit
// UPDATE
def update(msg: Msg, model: Model): (Model, Cmd) =
msg match {
case Quit => (model, Cmd.Empty)
case FileContentResult(Right(content)) =>
(content.asRight.some, Cmd.Empty)
case FileContentResult(Left(err)) =>
(err.getMessage.asLeft.some, Cmd.Empty)
case ReadFromFile(fileName) => (None, Cmd.ReadFromFile(fileName))
}
// IO
def io(model: Model, cmd: Cmd): IO[Msg] =
cmd match {
case Cmd.Empty =>
model match {
case None =>
Terminal.putStr("enter a file name> ") *> Terminal.readLine map ReadFromFile
case Some(Right(content)) =>
Terminal.putStrLn(content) map (_ => Quit)
case Some(Left(err)) =>
Terminal.putStrLn(s"error: $err") map (_ => Quit)
}
case Cmd.ReadFromFile(fileName) =>
FileSystem.readLines(fileName) map (_.map(_.mkString("\n"))) map FileContentResult
}
}