Skip to content

Commit

Permalink
Chapter 5.2 - IO
Browse files Browse the repository at this point in the history
  • Loading branch information
soupi committed May 8, 2022
1 parent ad34f22 commit 908e717
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 15 deletions.
53 changes: 53 additions & 0 deletions Main.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
-- Main.hs
module Main where

import qualified Markup
import qualified Html
import Convert (convert)

import System.Directory (doesFileExist)
import System.Environment (getArgs)

main :: IO ()
main = do
args <- getArgs
case args of
-- No program arguments: reading from stdin and writing to stdout
[] -> do
content <- getContents
putStrLn (process "Empty title" content)

-- With input and output file paths as program arguments
[input, output] -> do
content <- readFile input
exists <- doesFileExist output
let
writeResult = writeFile output (process input content)
if exists
then whenIO confirm writeResult
else writeResult

-- Any other kind of program arguments
_ ->
putStrLn "Usage: runghc Main.hs [-- <input-file> <output-file>]"

process :: Html.Title -> String -> String
process title = Html.render . convert title . Markup.parse

confirm :: IO Bool
confirm = do
putStrLn "Are you sure? (y/n)"
answer <- getLine
case answer of
"y" -> pure True
"n" -> pure False
_ -> do
putStrLn "Invalid response. use y or n"
confirm

whenIO :: IO Bool -> IO () -> IO ()
whenIO cond action = do
result <- cond
if result
then action
else pure ()
30 changes: 30 additions & 0 deletions example.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
* Compiling programs with ghc

Running ghc invokes the Glasgow Haskell Compiler (GHC),
and can be used to compile Haskell modules and programs into native
executables and libraries.

Create a new Haskell source file named hello.hs, and write
the following code in it:

> main = putStrLn "Hello, Haskell!"

Now, we can compile the program by invoking ghc with the file name:

> ➜ ghc hello.hs
> [1 of 1] Compiling Main ( hello.hs, hello.o )
> Linking hello ...

GHC created the following files:

- hello.hi - Haskell interface file
- hello.o - Object file, the output of the compiler before linking
- hello (or hello.exe on Microsoft Windows) - A native runnable executable.

GHC will produce an executable when the source file satisfies both conditions:

# Defines the main function in the source file
# Defines the module name to be Main, or does not have a module declaration

Otherwise, it will only produce the .o and .hi files.

15 changes: 0 additions & 15 deletions hello.hs

This file was deleted.

0 comments on commit 908e717

Please sign in to comment.