2013-01-09 49 views
1

這是我的代碼之前:操作變量(哈斯克爾)存儲

askPointer = do 
    input <- getLine 
    let newInput = map toUpper input 
    [..here I will re-use new Input..] 
    return() 

是否有可能(可能使用蘭巴表示法),以使此代碼中只有一條線短?

我的嘗試是不成功:

input <- (\a b-> do toUpper (b <- getLine)) 

任何建議?

編輯:小編輯,使這個問題尋找更通用的答案(不限制返回功能)

回答

3

這應該工作:

askPointer = getLine >>= return . map toUpper 

如果import Control.Applicative可以使其更短:

askPointer = map toUpper <$> getLine 

考慮最後編輯:

input <- getLine >>= return . map toUpper 

input <- map toUpper <$> getLine 
+0

如何獲得輸入值? – nick

+0

你能表達一點細節嗎? – nick

+1

@haskellguy:'輸入<- getLine >> =返回。 map toUpper'或'input < - map toUpper <$> getLine' – beerboy

6

在使用它之前應用到IO操作的結果的功能是什麼fmap做了出色的描述。

askPointer = do 
    newInput <- fmap (map toUpper) getLine 
    [..here I will re-use new Input..] 
    return() 

所以這裏fmap做你想要的到底是什麼 - 它適用於map toUppergetLine結果綁定,爲newInput之前。

在你的解釋嘗試這些了(ghci中/擁抱):

  1. fmap reverse getLine
  2. fmap tail getLine
  3. fmap head getLine
  4. fmap (map toUpper) getLine

如果import Data.Functorimport Control.Applicative,您可以使用中綴版本的fmap<$>

  1. reverse <$> getLine
  2. tail <$> getLine
  3. head <$> getLine
  4. map toUpper <$> getLine

,這意味着你也可以這樣寫

askPointer = do 
    newInput <- map toUpper <$> getLine 
    [..here I will re-use new Input..] 
    return() 

fmap確實是一個非常非常有用的功能。你可以在other answer about fmap中看到更多內容,我最終寫了一個迷你教程。