【发布时间】:2011-09-13 09:13:41
【问题描述】:
我编写了一个从 stdIn 读取的基本头模拟器:
import IO
import System
io lineList = interact (unlines . lineList . lines)
--Found this. Basically it takes all input from stdIn and reads it lazily.
main = do
[numLines] <- getArgs
io (take (read numLines))
--reads by lines.
然后我尝试像这样添加命令行(来源:http://leiffrenzel.de/papers/commandline-options-in-haskell.html)
import IO
import System
import System.Console.GetOpt
io lineList = interact (unlines . lineList . lines)
--Found this. Basically it takes all input from stdIn and reads it lazily.
main = do
args <- getArgs
let ( actions, nonOpts, msgs ) = getOpt RequireOrder options args
opts <- foldl (>>=) (return defaultOptions) actions
let Options { optNum = input,
optOut = output} = opts
input >>= output
data Options = Options {
optNum :: IO String,
optOut :: String -> IO ()
}
defaultOptions :: Options
defaultOptions = Options {
optNum = "10",
optOut = io (take optNum)
}
options :: [OptDescr (Options -> IO Options)]
options = [
Option ['n'] ["numlines"] (OptArg readNumLines ) "read x amount of lines"
]
readNumLines arg opt = return opt (go arg)
go w = io (take (read w))
--reads by lines.
现在,我在这里的经验已经不多了。如果设置了 N 开关,我实际上调用 readNumLines 的唯一地方似乎是选项。现在,如果没有设置 N 开关,我想运行 arg 为 10 的 readNumLines 命令。我显然没有这样做。
提前致谢:)
编辑:所以,在对我的代码进行了一些拖钓之后,我已经将其置于不会向我抛出任何错误但仍无法编译的状态:不在范围内:数据构造函数“选项” ,但我已经定义了选项?编辑:我已经更改了 Options 构造函数,但现在它告诉我它无法将 IO Options 的预期类型与实际类型 Options 匹配 opts >=) (return defaultOptions) 动作
我尝试删除操作,但没有成功。
编辑:所以我删除了大部分有问题的行,它起作用了。
opts
但是,传递 -n 并没有做任何事情,它只返回前 10 行。
【问题讨论】:
-
拖钓代码从来都不是一件好事。导致不必要的不安,IMO。
标签: haskell command-line-arguments argument-passing