Last active
May 6, 2023 15:39
-
-
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/aa64c9950e867ddb253ab8a491f0cff574f6db24
This file contains 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
// 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.2.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