# Lazy countmap

**URL:** <https://discourse.julialang.org/t/lazy-countmap/35220>\
**Category:** General Usage\
**Tags:** lazy-evaluation\
**Created:** [February 27, 2020, 9:45am UTC](https://discourse.julialang.org/t/lazy-countmap/35220 "2020-02-27T09:45:28Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![harven](https://avatars.discourse-cdn.com/v4/letter/h/3da27b/32.png) [@harven](https://discourse.julialang.org/u/harven)\
**Post date:** [February 27, 2020, 9:45am UTC](https://discourse.julialang.org/t/lazy-countmap/35220/1 "2020-02-27T09:45:28Z")

</div>

I am triaging elements in a list according to their values by some function f and compute the number of elements for each possible value as follows.

> countmap(map(f, list))

This returns a dict whose keys are unique values of f and values are the number of occurrence of elements in the list with these values.

I would like to make a lazy version of the preceding code, like

> mapcount(f(x) for x in gen)

but mapcount does not take a generator as argument. Is there a lazy version of mapcount in some library? I have looked at Iterators and Itertools but I don’t think I saw it.

Arguably a lazy mapcount is not very hard to implement but this is a basic task so I guess it must be somewhere. Maybe in some statistical package a la R which uses lazy evaluation? StatsBase seems to be strict.

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [February 27, 2020, 10:09am UTC](https://discourse.julialang.org/t/lazy-countmap/35220/2 "2020-02-27T10:09:15Z")

</div>

AFAICT accumulators in `DataStructures` support generic iterables. Combine with `IterTools.imap`.

---

<div class="post-metadata">

**Author:** ![piever](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/piever/32/1815_2.png) [@piever](https://discourse.julialang.org/u/piever)\
**Post date:** [February 27, 2020, 12:55pm UTC](https://discourse.julialang.org/t/lazy-countmap/35220/3 "2020-02-27T12:55:14Z")

</div>

OnlineStats also has a [CountMap](https://joshday.github.io/OnlineStats.jl/latest/api/#OnlineStatsBase.CountMap) that can be fit by iterating once through the data.

---

<div class="post-metadata">

**Author:** ![harven](https://avatars.discourse-cdn.com/v4/letter/h/3da27b/32.png) [@harven](https://discourse.julialang.org/u/harven)\
**Post date:** [February 27, 2020, 3:27pm UTC](https://discourse.julialang.org/t/lazy-countmap/35220/4 "2020-02-27T15:27:27Z")

</div>

Thanks for the answer. I finally went with `DataStructures.counter`.

```
   counter(f(x) for x in gen).map

```
