简体   繁体   English

如何修复简单的Haskell CLI程序以显示文件内容?

[英]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 ). 因此,我将遍历CmdArgs文档中的示例,并尝试构建Hello World程序,以制作一个简单的CLI程序,该程序以文件名作为输入,并仅显示该文件的内容(例如cat )。 But I'm a Haskell beginner, and have virtually no idea what I'm doing. 但是我是Haskell的初学者,几乎不知道我在做什么。 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: 因此,运行runhaskell mycat.hs test.txt显示:

ShowFile {file = Just "test.txt"}

So something's working! 所以有些事情在起作用! Now how do I get it to display the contents of test.txt instead? 现在如何获取它来显示test.txt的内容呢? 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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