2017-05-14 53 views
1

我怎麼會去有關轉換的字符串這樣"13.2..2"到列表這樣如何將字符串轉換爲的也許詮釋

[Just 1, Just 3, Nothing, Just 2, Nothing, Nothing, Just 2]

名單我已經在digitToInt一看,但它確實沒有照顧Maybe Int。有沒有辦法我可以修改digitToInt來處理Maybe Int

+2

爲什麼所有的關閉/低票?這絕對不是「太寬泛」,很清楚要問什麼。 –

回答

3

如果希望所有非數字轉換爲Nothing,則CA氮利用警衛和fmap

import Data.Char 

charToMaybeInt :: Char -> Maybe Int 
charToMaybeInt x 
| isDigit x = Just $ digitToInt x 
| otherwise = Nothing 

main = putStrLn $ show $ fmap charToMaybeInt "13.2..2" 

使用衛士是,從我的非專業的認識,有點比使用if/else更地道。

7

您可以使用isDigit來測試digitToInt是否會成功。

λ> fmap (\c -> if isDigit c then Just (digitToInt c) else Nothing) "13.2..2" :: [Maybe Int] 
[Just 1, Just 3, Nothing, Just 2, Nothing, Nothing, Just 2] 

我們可以引入一個新的函數清理它一點:

digitToIntMay :: Char -> Maybe Int 
digitToIntMay c = if isDigit c then Just (digitToInt c) else Nothing 

λ> fmap digitToIntMay "13.2..2" :: [Maybe Int] 
[Just 1, Just 3, Nothing, Just 2, Nothing, Nothing, Just 2] 
0

如果你是某個數據來絕對是一個數字或.(或者是高興異常被拋出,如果的數據是不同的),可以使用模式匹配和fmap

import Data.Char 

chatToMaybeInt :: Char -> Maybe Int 
chatToMaybeInt '.' = Nothing 
chatToMaybeInt x = Just $ digitToInt x 

main = putStrLn $ show $ fmap chatToMaybeInt "13.2..2" 
+0

兩個答案?!?爲什麼不把這兩個合併爲一個呢? –

+0

@StephaneRolland因爲它們不同:它們使用不同的代碼,語言特徵並具有不同的優點/缺點。例如,這個可以拋出異常,OP /選民可能找不到合適的例外。從我可以告訴,多個答案可以接受https://meta.stackexchange.com/questions/25209/what-is-the-official-etiquette-on-answering-a-question-twice。 –