2012-01-18 286 views
6

我正在研究以下代碼,並希望找到該字符串中數字的索引。所以我用findIndex,但它返回Maybe Int值,而我只想要Int值。在Haskell中將Maybe Int轉換爲Int

我該如何將Maybe Int轉換爲Int值或者有沒有什麼方法可以從Maybe Int中提取Int。該代碼應打印錯誤信息,如果可能int是什麼

box:: String 
box = unlines $ ["0 | 1 | 2", 
       "---------", 
       "3 | 4 | 5", 
       "---------", 
       "6 | 7 | 8"] 

moves = do 
     putStrLn " Enter the number" 
     number <- readLn :: IO Int 
     print number 
     findpostion number box 

findposition number box = findIndex (==number) box 

回答

16

您可以輕鬆地做到這一點使用模式匹配您的do聲明:

case findposition number box of 
    Just n -> -- do whatever with n 
    Nothing -> putStrLn "Invalid number!" -- you can handle the error however you want. 

一個很好的選擇是創建一個單獨的IO動作得到號碼:

getNumber = do putStrLn "Enter the number:" 
       number <- readLn 
       case findposition number box of 
       Just n -> -- Do whatever 
       Nothing -> putStrLn "Please try again." >> getNumber 

這樣如果用戶輸入一個無效號碼,它只是再次詢問。

此外,正如現在寫的,您的代碼將無法工作。您應該有其他方式將box中的數字存儲爲實際數字;現在,他們在Strings中。

+0

其實,其目的是要找到用戶輸入的號碼,稍後用任何其他字符替換它說'x' – 2012-01-18 05:03:54

+0

啊。在這種情況下,由於您正在查看字符串,因此您需要讀入「Char」而不是「Int」。實際上,你應該完全可以忽略':: IO Int'位。 – 2012-01-18 05:06:40

+0

好的,謝謝..我會試試這個,一定會回覆你... – 2012-01-18 05:09:52

10

很顯然,這是不可能的一般:當搜索不成功沒有規範的整數返回值,所以你得到一個Nothing沒有任何這樣的值然後。

如果你真的不關心Nothing情況下(例如,因爲你永遠確保有一個這樣的元素),你可以使用fromJust功能出Data.Maybe,你也可以快速實現自己:

findposition number = (\(Just i)->i) . findIndex (==number) 

但是這並不是真的值得推薦,因爲你的需要確保這不會中斷,並通過適當的模式匹配來做到這一點更容易。

+0

他提到他想在「Nothing」上「返回錯誤信息」。雖然這有些模糊,但我認爲只要打印錯誤而不是讓程序崩潰,他會很高興。 – 2012-01-18 05:48:35

+4

如果在你正在工作的上下文中有*是一個「規範整數」,那麼你可以在'canonicalInt :: Int'和'maybeVal :: Maybe Int'中使用'fromMaybe canonicalInt maybeVal'。請參閱[Data.Maybe文檔](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Maybe.html#v:fromMaybe) – 2012-01-18 06:50:19