在爲System.Console.GetOpt文檔中給出的第二個例子,在這裏重現,我無法理解或解開這一行:getopt的使用和與foldl,翻轉,ID
(o,n,[] ) -> return (foldl (flip id) defaultOptions o, n)
這是什麼與foldl在做什麼,它是如何實現的? (flip id)的用途是什麼?到底是怎麼回事?
代碼:
import System.Console.GetOpt
import Data.Maybe (fromMaybe)
data Options = Options
{ optVerbose :: Bool
, optShowVersion :: Bool
, optOutput :: Maybe FilePath
, optInput :: Maybe FilePath
, optLibDirs :: [FilePath]
} deriving Show
defaultOptions = Options
{ optVerbose = False
, optShowVersion = False
, optOutput = Nothing
, optInput = Nothing
, optLibDirs = []
}
options :: [OptDescr (Options -> Options)]
options =
[ Option ['v'] ["verbose"]
(NoArg (\ opts -> opts { optVerbose = True }))
"chatty output on stderr"
, Option ['V','?'] ["version"]
(NoArg (\ opts -> opts { optShowVersion = True }))
"show version number"
, Option ['o'] ["output"]
(OptArg ((\ f opts -> opts { optOutput = Just f }) . fromMaybe "output")
"FILE")
"output FILE"
, Option ['c'] []
(OptArg ((\ f opts -> opts { optInput = Just f }) . fromMaybe "input")
"FILE")
"input FILE"
, Option ['L'] ["libdir"]
(ReqArg (\ d opts -> opts { optLibDirs = optLibDirs opts ++ [d] }) "DIR")
"library directory"
]
compilerOpts :: [String] -> IO (Options, [String])
compilerOpts argv =
case getOpt Permute options argv of
(o,n,[] ) -> return (foldl (flip id) defaultOptions o, n)
(_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))
where header = "Usage: ic [OPTION...] files..."
嘗試在GHCi上鍵入':t flip id'。這也相當於'(,)(foldl(flip id)defaultOptions o)n'。 – Mephy
是的,但變量o如何應用於defaultOptions變量,foldl使用的實際函數是什麼? – andro
我可能會寫'flip id'作爲'flip($)',因爲後者使意圖更加明顯。 – chi