像catMaybes这样的函数,但计数Nothing值 [英] Function like catMaybes, but counting Nothing values

查看:156
本文介绍了像catMaybes这样的函数,但计数Nothing值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个列表:

  let foo = [只有1,只有2,没有,只有3,没有,Nothing] 

通过使用 catMaybes 我只能提取 Just
pre $ catMaybes foo - [1,2,3]

我现在正在寻找一个不仅产生 Just 列表的函数, s,而且通过遍历一次有限清单的计数为 Nothing s。它应该有这样的签名:

  catMaybesCount :: [也许a]  - > ([a],Int)

注意: ; A风格,因此故意不显示任何研究工作!

解决方案

  import Data .Monoid 
import Data.Foldable
$ b $ catMaybesCount = foldMap注入其中
注入Nothing =([],Sum 1)
inject(Just x)=([x ],Sum 0)


I have a list like this:

let foo = [Just 1, Just 2, Nothing, Just 3, Nothing, Nothing]

By using catMaybes I can extract only the Just-constructed values:

catMaybes foo -- [1,2,3]

I'm now looking for a function that not only yields a list of Justs but also a count of Nothings for a finite list by traversing it once. It should have a signature like this:

catMaybesCount :: [Maybe a] -> ([a], Int)

Note: This question was answered Q&A-style and therefore intentionally does not show any research effort!

解决方案

import Data.Monoid
import Data.Foldable

catMaybesCount = foldMap inject where
    inject Nothing  = ([ ], Sum 1)
    inject (Just x) = ([x], Sum 0)

这篇关于像catMaybes这样的函数,但计数Nothing值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆