存储在变量(Haskell)之前对用户getLine结果的操作

pig*_*ack 1 haskell

这是我的代码:

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

是否可能(可能使用lamba表示法),只在一行中缩短此代码?

我的尝试失败了:

input <- (\a b-> do toUpper (b <- getLine ) )
Run Code Online (Sandbox Code Playgroud)

有什么建议?

编辑:很少编辑,使这个问题寻找更通用的答案(不限于返回功能)

And*_*ewC 6

在使用之前将函数应用于IO操作的结果是一个很好的描述fmap.

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

所以这里fmap完全符合您的要求 - 它适用map toUppergetLine绑定之前的结果newInput.

在你的翻译中尝试这些(ghci/hugs):

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

如果你import Data.Functor或者import 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 ()
Run Code Online (Sandbox Code Playgroud)

fmap确实是一个非常有用的功能.您可以在关于fmap的其他答案中阅读更多内容,我最终编写了一个迷你教程.