Last active
December 17, 2022 15:32
-
-
Save rohinp/19e498cb496a2bb0e57cb47c5aed35e4 to your computer and use it in GitHub Desktop.
Gist for the blog FunctionDay0
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
object DummyFile: | |
case class File( `type`:File.Type, content:String) | |
object File: | |
enum Type: | |
case TEXT, PRESENTATION, AUDIO, VIDEO, UNKNOWN | |
end File | |
end DummyFile |
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
import scala.util.* | |
import DummyFile.* | |
object FunctionDay0: | |
enum FileParserResult: | |
case Success(content:String) | |
case GoNext | |
case Failure(errorMsgs:String) | |
def parser:File.Type => File => FileParserResult = | |
fileType => file => | |
Try { | |
fileType match | |
case File.Type.UNKNOWN => | |
FileParserResult.Failure(s"The File type is not supported.") | |
case matchedType if file.`type` == matchedType => | |
FileParserResult.Success(file.content) | |
case otherwise => FileParserResult.GoNext | |
} match { | |
case Success(result) => result | |
case Failure(err) => FileParserResult.Failure( | |
s"Failed due to error ${err.getMessage}" | |
) | |
} | |
implicit class ParserComposeOps(func: File => FileParserResult): | |
def >>>(nextFunction: File => FileParserResult): File => FileParserResult = | |
file => | |
func(file) match | |
case FileParserResult.GoNext => | |
nextFunction(file) | |
case errorOrSuccess => | |
errorOrSuccess | |
val mainParser:File => FileParserResult = | |
parser(File.Type.TEXT) | |
>>> parser(File.Type.PRESENTATION) | |
>>> parser(File.Type.AUDIO) | |
>>> parser(File.Type.VIDEO) | |
>>> parser(File.Type.UNKNOWN) | |
end FunctionDay0 | |
@main def fileParser = | |
import FunctionDay0.* | |
val myFile = File(File.Type.TEXT, "Some text file") | |
println(mainParser(myFile)) | |
val errorFile = File(File.Type.UNKNOWN, "This is not a known file type.") | |
println(mainParser(errorFile)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment