2017-09-12 89 views
0

選擇如何實現從grep --help這個例子解析器:解析「枚舉」與optparse,應用性

--binary-files=TYPE assume that binary files are TYPE; 
         TYPE is 'binary', 'text', or 'without-match' 

假設我有

data BinaryFiles = Binary | Text | WithoutMatch 

我怎樣寫一個解析器? option auto似乎是一個kludge因爲Read應該是一個「反」Show,我想保留導出instance Show BinaryFiles

回答

4

使用str代替auto

binFile :: ReadM BinaryFiles 
binFile = str >>= \s -> case s of 
    "binary"  -> return Binary 
    "text"   -> return Text 
    "without-match" -> return WithoutMatch 
    _ -> readerError "Accepted binary file types are 'binary', 'text', and 'without-match'."