gpt4 book ai didi

haskell - 在 Haskell 中解析命令行参数

转载 作者:行者123 更新时间:2023-12-02 12:43:43 26 4
gpt4 key购买 nike

我目前正在开发一个需要解析命令行参数的项目。到目前为止我一直在关注this tutorial ,这非常有帮助,但我不知道如何在参数中返回变量(--author=example)。我也无法弄清楚为什么 parse [] = getContents 会导致错误(我不得不取消注释它)。

这是我的代码:

module Main where

import qualified System.Environment as SE
import qualified System.Exit as E
import qualified Lib as Lib

main = do
args <- SE.getArgs
rem <- parse args
Lib.someFunc
putStrLn rem
putStrLn "Hello"

tac = unlines . reverse . lines

parse ["--help"] = usage >> exit
parse ["--version"] = version >> exit
parse ["--author=xyz"] = return "xyz"
-- parse ["--author=?"] = ?
{-
this is the code I am trying to figure out... how do I get parse the passed in variable name?
-}

-- parse [] = getContents
{-
the above line generates this error when I run 'main' in GHCi:

*Main> <stdin>: hIsEOF: illegal operation (handle is semi-closed)
Process intero exited abnormally with code 1

-}
parse fs = concat `fmap` mapM readFile fs

usage = putStrLn "Usage: gc2"
version = putStrLn "gc2 -- git-cal in Haskell2010 - 0.1"
exit = E.exitWith E.ExitSuccess
die = E.exitWith (E.ExitFailure 1)

最佳答案

跟进 @ThomasM.DuBuisson 评论 optparse-applicative是一个很棒的 cli 和参数解析包。还有另一个包optparse-simple它建立在前一个之上,并且有一些帮助程序可以稍微简化事情。

为了让您可以开始使用optparse-applicative,这里是您的示例的实现:

data Options = Options
{ author :: String
}

main :: IO ()
main = do
let ver = "gc2 -- git-cal in Haskell2010 - 0.1"
args <-
execParser $
info
(Options <$>
strOption (long "author" <>
short 'a' <>
help "Name of the author.") <*
infoOption ver (long "version" <>
short 'v' <>
help "Display version and exit.") <*
abortOption ShowHelpText (long "help" <>
short 'h' <>
help "Display this message."))
(progDesc "Very powerful tool." <> fullDesc)
putStrLn $ author args

GHCi 的使用示例:

λ> :main
Missing: (-a|--author ARG)

Usage: <interactive> (-a|--author ARG) [-v|--version] [-h|--help]
Very powerful tool.
*** Exception: ExitFailure 1
λ> :main --version
gc2 -- git-cal in Haskell2010 - 0.1
*** Exception: ExitSuccess
λ> :main --help
Usage: <interactive> (-a|--author ARG) [-v|--version] [-h|--help]
Very powerful tool.

Available options:
-a,--author ARG Name of the author.
-v,--version Display version and exit.
-h,--help Display this message.
*** Exception: ExitSuccess
λ> :main --author Me
Me

关于haskell - 在 Haskell 中解析命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47683804/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com