这是我的代码:
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)
有什么建议?
编辑:很少编辑,使这个问题寻找更通用的答案(不限于返回功能)
在使用之前将函数应用于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 toUpper于getLine绑定之前的结果newInput.
在你的翻译中尝试这些(ghci/hugs):
fmap reverse getLinefmap tail getLinefmap head getLinefmap (map toUpper) getLine如果你import Data.Functor或者import Control.Applicative,你可以使用的版本中缀fmap,<$>:
reverse <$> getLinetail <$> getLinehead <$> getLinemap toUpper <$> getLine这意味着你也可以写
askPointer = do
newInput <- map toUpper <$> getLine
[..here I will re-use new Input..]
return ()
Run Code Online (Sandbox Code Playgroud)
fmap确实是一个非常有用的功能.您可以在关于fmap的其他答案中阅读更多内容,我最终编写了一个迷你教程.
| 归档时间: |
|
| 查看次数: |
186 次 |
| 最近记录: |