本文介绍了在Haskell中总结Maybe Int列表的习惯用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有更实用的方法来实现以下目标?我觉得我错过了一种摆脱拉姆达的方式,但无法找到将其转换为无点的方法。也许还有另一种非应用方式,那就更简单了?import Data.Maybe
import Control (只有0)[只有3,只有4]
(\ xy - >纯(+)* x * y) - 只有7
foldl(\ xy - >纯(+)* x * y)(只是0)[只有3,只有4,没有]
- Nothing
解决方案
从Control.Monad使用 sequence :
> fmap sum $ sequence [Just 3,Just 4]
只需7
> fmap sum $ sequence [Just 3,Just 4,Nothing]
Nothing
- 免费表格:
sumMaybe :: Num a => [也许a] - >也许
sumMaybe = fmap总和。序列
Is there a more idiomatic way to implement the following? I feel like I'm missing a way to get rid of the lambda, but couldn't figure out a way to convert it to point-free. Maybe there is another non-applicative way as well that is more straight forward?
import Data.Maybe import Control.Applicative foldl (\x y -> pure (+) <*> x <*> y) (Just 0) [Just 3, Just 4] -- Just 7 foldl (\x y -> pure (+) <*> x <*> y) (Just 0) [Just 3, Just 4, Nothing] -- Nothing
解决方案
I'd just use sequence from Control.Monad:
> fmap sum $ sequence [Just 3, Just 4] Just 7 > fmap sum $ sequence [Just 3, Just 4, Nothing] Nothing
For the point-free form:
sumMaybe :: Num a => [Maybe a] -> Maybe a sumMaybe = fmap sum . sequence
这篇关于在Haskell中总结Maybe Int列表的习惯用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!