Last active
February 3, 2026 20:19
-
-
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/7d0900d2f9c483009c65f524e5ae94865acb7c1a
This file contains hidden or 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 License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // 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