# Generalizing aggregate/3 by adding foldl semantics

**URL:** <https://swi-prolog.discourse.group/t/generalizing-aggregate-3-by-adding-foldl-semantics/7549>\
**Category:** Discussion\
**Tags:** discussion\
**Created:** [June 23, 2024, 4:54pm UTC](https://swi-prolog.discourse.group/t/generalizing-aggregate-3-by-adding-foldl-semantics/7549 "2024-06-23T16:54:31Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![peter.ludemann](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/peter.ludemann/32/48_2.png) [@peter.ludemann](https://swi-prolog.discourse.group/u/peter.ludemann)\
**Post date:** [June 23, 2024, 4:54pm UTC](https://swi-prolog.discourse.group/t/generalizing-aggregate-3-by-adding-foldl-semantics/7549/1 "2024-06-23T16:54:31Z")

</div>

The [aggregation library](https://www.swi-prolog.org/pldoc/man?section=aggregate) supports `count`, `sum`, `min`, `max`, etc.

A generalization of this would be to use foldl/4 semantics. For example, the `sum` operator could be implemented by `aggregate(foldl(plus), Goal, 0, Result)`.

It might also be useful to have a post-aggregation option – e.g., the `setof` operator could be implemented by `foldl(app)` + sort/2 (where `app/3` is defined: `app(X,Xs,[X|Xs])`). (It’s not clear to me how to efficiently define the `bagof` operator; a `reverse_bagof` is easy, using this predicate: `reverse_append(X,Xs,[X|Xs])`.)
