Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
haskell中求整型列表的惯用方法_Haskell - Fatal编程技术网

haskell中求整型列表的惯用方法

haskell中求整型列表的惯用方法,haskell,Haskell,有没有更惯用的方法来实现以下内容?我觉得我错过了一个摆脱lambda的方法,但却找不到一个将其转换为无点的方法。也许还有另一种更直接的非应用性方法 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 &l

有没有更惯用的方法来实现以下内容?我觉得我错过了一个摆脱lambda的方法,但却找不到一个将其转换为无点的方法。也许还有另一种更直接的非应用性方法

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
导入数据。可能吧
导入控制
foldl(\xy->纯(+)xy)(仅0)[仅3,仅4]
--只有7个
foldl(\x y->pure(+)x y)(仅0)[仅3,仅4,无]
--没什么

我认为
foldM
在这里很有效

import Control.Monad
sumMay = foldM (fmap . (+)) 0

我认为这是最清晰的,因为它将(Ba-duh-duh-ching)映射到纯代码中所做的事情。

我只使用Control中的
序列。Monad:

> fmap sum $ sequence [Just 3, Just 4]
Just 7
> fmap sum $ sequence [Just 3, Just 4, Nothing]
Nothing
对于无点形式:

sumMaybe :: Num a => [Maybe a] -> Maybe a
sumMaybe = fmap sum . sequence
您可以使用以下方法提升菜单中的(+):

input> fold (liftM2 (+)) (Just 0) [Just 1, Just 2]
Just 3
input> fold (liftM2 (+)) (Just 0) [Just 1, Just 2, Nothing]
Nothing

消除lambda最直接的方法是使用
liftA2
;这正是你写的代码

liftA2 :: (a -> b -> c) -> f a -> f b -> f c
liftA2 f x y = pure f <*> x <*> y

foldl (liftA2 (+)) (Just 0) [Just 1, Just 2]
我们还可以利用
(+)
在值上诱导一个
幺半群
的事实,以便“忽略”
什么都不做。从字面上说,这应该是

import Data.Monoid

getSum $ foldMap (maybe mempty Sum) [Just 1, Just 2, Nothing]
-- equivalent to, but faster than
getSum . mconcat . map (maybe mempty Sum) $ [Just 1, Just 2, Nothing]
getSum . mconcat $ [Sum 1, Sum 2, Sum 0]
3
但是我们也可以使用
Data.Monoid
中的
catMaybe
分两步完成

sum . catMaybes $ [Just 1, Just 2, Nothing]
sum [1, 2]
3

另外,请注意
(纯f)≡ (f)
(其中
fmap
的中缀形式)。第二个示例(当任何元素为
Nothing
时,需要返回
Nothing
)无法使用ghci 7.6.3进行计算,但可以使用7.8.3
sum . catMaybes $ [Just 1, Just 2, Nothing]
sum [1, 2]
3
import Data.Maybe
import Data.List
sumMaybes = sum . catMaybes