Write CLI scripts in Elm (IO Monad)

I found the andThen pattern to be quite readable and avoids those wildcard parameters:

module HelloFile exposing (program)

import Posix.IO as IO exposing (IO, Process)
import Posix.IO.File as File
import Posix.IO.Process as Proc


program : Process -> IO ()
program process =
    case process.argv of
        [ _, inName ] ->
            -- Print to stdout if no output file provided
            File.contentsOf inName
                |> IO.exitOnError identity
                |> IO.andThen (processContent >> Proc.print)

        [ _, inName, outName ] ->
            File.contentsOf inName
                |> IO.exitOnError identity
                |> IO.andThen (processContent >> File.writeContentsTo outName)

        _ ->
            Proc.logErr "Error: Provide the names of the input file and optionally an output file.\n"


processContent : String -> String
processContent =
    -- Do something with the content of the input file here.
    String.toUpper

1 Like