2013-01-09 50 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中看到更多内容,我最终写了一个迷你教程。