目前我有一個功能getFP :: IO [String] -> Maybe (FilePath)。getFP [] = Nothing如果引數是非 IO 字串,我想做的是等效的。我怎么能這樣做?謝謝你:p
uj5u.com熱心網友回復:
IO [String]是可以產生的動作[String]。沒有辦法將其轉換為純值Maybe FilePath,但您可以輕松地將其與純函陣列合以獲取另一個操作。do一種方法是用符號寫出來。例如,假設您想要第一個路徑:
getFP :: IO [String] -> IO (Maybe FilePath)
getFP action = do
strings <- action
case strings of
path : _ -> pure (Just path)
[] -> pure Nothing
這可能像getFP loadPathswhere loadPathsis some action like lines <$> readFile "paths.txt"that return a list of file paths 一樣使用。但是,如果您要立即運行該操作,則將純值作為引數而不是操作更為常見。
getFP :: [String] -> IO (Maybe FilePath)
getFP strings =
case strings of
path : _ -> pure (Just path)
[] -> pure Nothing
那將被稱為getFP =<< loadPaths.
現在不需要IOin getFP,因為它使用的唯一IO動作是pure.
getFP :: [String] -> Maybe FilePath
getFP strings =
case strings of
path : _ -> Just path
[] -> Nothing
這可以像getFP <$> loadPaths. (此外,在此示例中,它現在等效于listToMaybe來自的標準函式Data.List。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528531.html
標籤:哈斯克尔io单子
