简体   繁体   中英

How can I fix my simple Haskell CLI program to show the contents of a file?

So I'm going through the examples in the CmdArgs documentation , and I'm trying to build off the Hello World program in order to make a simple CLI program that takes a filename as input, and just shows the contents of that file (like cat ). But I'm a Haskell beginner, and have virtually no idea what I'm doing. Here's what I have so far:

{-# LANGUAGE DeriveDataTypeable #-}
module ShowFile where
import System.Console.CmdArgs

data ShowFile = ShowFile {file :: Maybe FilePath}
              deriving (Show, Data, Typeable)

showFile = ShowFile
  {file = def &= typ "FILE" &= argPos 0}

main = print =<< cmdArgs showFile

And so running runhaskell mycat.hs test.txt shows:

ShowFile {file = Just "test.txt"}

So something's working! Now how do I get it to display the contents of test.txt instead? I've been trying things like:

main = getContents showFile

but haven't stumbled on the right thing yet.

Pattern match on the option.

main = do
    options <- cmdArgs showFile
    contents <- case options of
        ShowFile { file = Nothing } -> getContents
        ShowFile { file = Just f  } -> readFile f
    putStr contents

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM