gpt4 book ai didi

Haskell:Turtle:命令行解析器

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

我一直在尝试用 Turtle 构建一个命令行解析器,没什么花哨的:https://github.com/Tyrn/go-procr

#!/usr/bin/env stack
{-# LANGUAGE OverloadedStrings #-}

module Main where

import Turtle
import Prelude hiding (FilePath)

parserSwitch :: Parser (Bool, Bool)
parserSwitch = (,) <$> switch "verbose" 'v' "Unless verbose, just progress bar is shown"
<*> switch "filetitle" 'f' "Use file name for title tag"

parserArg :: Parser (FilePath, FilePath)
parserArg = (,) <$> argPath "src" "Source directory"
<*> argPath "dst" "Destination directory"

main :: IO ()
main = do
(verbose, filetitle) <- options "Flags" parserSwitch
echo (format ("verbose: "%w) verbose)
echo (format ("filetitle: "%w) filetitle)
(src, dst) <- options "Args" parserArg
echo (format ("src: "%fp) src)
echo (format ("dst: "%fp) dst)

需要三种参数: bool 标志;选项、文本和整数;位置参数。到目前为止,我陷入了 bool 标志和位置参数的困境。不幸的是,即使如此,这些例子似乎也太基础了。

  1. 我真的必须为不同类型的选项构建单独的解析器(我无法用单个解析器满足语法要求)吗?

  2. 无论如何,它都不会按预期工作。

我不知道下一步应该做什么。

最佳答案

您的第一步是拥有可以轻松存储和检索选项的东西:

data Settings = Settings
{ settingsVerbose :: Bool
, settingsFileTitle :: Bool
, settingsSource :: FilePath
, settingsDestination :: FilePath
}

然后,您为您的选项编写解析器。为了让事情变得清楚,让我们先说得详细一些:

verboseParser :: Parser Bool
verboseParser = switch "verbose" 'v' "Be more verbose"

fileTitleParser :: Parser Bool
fileTitleParser = switch "filetitle" 'f' "..."

sourceParser :: Parser FilePath
sourceParser = argPath "src" "Source directory"

destinationParser :: Parser FilePath
destinationParser = argPath "dst" "Destination directory"

由于 ParserApplicative 的实例,因此我们可以将所有选项组合在一个解析器中:

settingsParser :: Parser Settings
settingsParser =
Settings <$> verboseParser
<*> fileTitleParser
<*> sourceParser
<*> destinationParser

我们将所有四个解析器组合成一个解析器,类似于通过 (,) 进行的组合。现在我们可以通过单次调用options来解析选项。毕竟,要么所有参数都是正确的,要么我们必须向用户展示正确的用法:

main = do
s <- options "Description of your program" settingsParser

echo (format ("verbose: "%w) (settingsVerbose s))
echo (format ("filetitle: "%w) (settingsFileTitle s))
echo (format ("src: "%fp) (settingsSource s))
echo (format ("dst: "%fp) (settingsDestination s))

不过,您可能想使用较短的名称,并且可能在 settingsParser 中编写解析器:

data Settings = Settings
{ sVerbose :: Bool
, sFileTitle :: Bool
, sSource :: FilePath
, sDestination :: FilePath
}

settingsP :: Parser Settings
settingsP =
Settings <$> switch "verbose" 'v' "Be more verbose"
<*> switch "filetitle" 'f' "..."
<*> argPath "src" "Source directory"
<*> argPath "dest" "Destination directory"

description :: Description
description = "Description of your program"

main = do
(Settings verbose filetitle source dest) <- options description settingsP
...

关于Haskell:Turtle:命令行解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35463892/

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