Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 25, 2024 10:19
Show Gist options
  • Save dacr/b1221f5d3a1ca1130d4b96a68e0f8596 to your computer and use it in GitHub Desktop.
Save dacr/b1221f5d3a1ca1130d4b96a68e0f8596 to your computer and use it in GitHub Desktop.
ZIO learning - playing with streams - stream based grep implementation / published by https://github.com/dacr/code-examples-manager #32c91a86-e72f-42ae-878d-5cd8e68935d5/b53b70fed50aa5ce03037652e7318c3c4b1e3dde
// summary : ZIO learning - playing with streams - stream based grep implementation
// keywords : scala, zio, learning, streams, grep
// publish : gist
// authors : zio
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 32c91a86-e72f-42ae-878d-5cd8e68935d5
// created-on : 2021-10-30T23:09:55+02:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// usage-example : scl zio-learning-streams-2-grep.sc -- '.*getArgs' zio-learning-streams-2-grep.sc
// ---------------------
//> using scala "3.4.2"
//> using dep "dev.zio::zio:2.0.13"
//> using dep "dev.zio::zio-streams:2.0.13"
// ---------------------
import zio.*
import zio.stream.*
import java.nio.file.Paths
import zio.stream.ZPipeline.{splitLines, utf8Decode}
import scala.util.matching.Regex
object Grep extends ZIOAppDefault {
def grepStream(inputFile: String, regex: Regex) =
ZStream
.fromFile(Paths.get(inputFile).toFile)
.via(utf8Decode >>> splitLines)
.filter(line => regex.findFirstIn(line).isDefined)
val run =
for {
args <- getArgs
pattern <- ZIO.from(args.headOption).tapError(_ => Console.printLine("grep pattern not provided"))
filename <- ZIO.from(args.drop(1).headOption).tapError(_ => Console.printLine("grep filename not provided"))
regex <- ZIO.attempt(pattern.r)
foundResults <- grepStream(filename, regex).runCollect
_ <- ZIO.foreach(foundResults)(matchingLine => Console.printLine(matchingLine))
} yield ()
}
Grep.main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment