Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example for accumulate and accumulate2 #261

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

erichaney
Copy link
Contributor

No description provided.

@sogaiu sogaiu marked this pull request as draft January 17, 2025 04:07
@sogaiu
Copy link
Collaborator

sogaiu commented Jan 17, 2025

I wonder about the behavior of reduce2 in this example:

(reduce2 + []) # -> nil

May be it could be considered a bug.

reduce2's docstring is currently:

The 2-argument version of reduce that does not take an initialization value. Instead, the first element of the array is used for initialization.

[] has no first element so the intent doesn't seem explicitly specified according to the docstring.


In these kinds of cases, it seems preferable to me to not record these as examples until further clarification so I've marked the PR as a draft.

@sogaiu
Copy link
Collaborator

sogaiu commented Jan 17, 2025

For comparison, reduce in Clojure can be called in two ways:

(reduce f coll) (reduce f val coll)

f should be a function of 2 arguments. If val is not supplied, returns the result of applying f to the first 2 items in coll, then applying f to that result and the 3rd item, etc. If coll contains no items, f must accept no arguments as well, and reduce returns the result of calling f with no arguments.

via: https://clojuredocs.org/clojure.core/reduce

The actual behavior in the following case (2-argument call) seems to match the docstring:

$ clj
Clojure 1.12.0
user=> (reduce + [])
0

May be that was inspired by Common Lisp's reduce as that seems consistent with this:

If the subsequence is empty and no initial-value is given, then the function is called with zero arguments, and reduce returns whatever function does. This is the only case where the function is called with other than two arguments.

via: https://www.lispworks.com/documentation/HyperSpec/Body/f_reduce.htm#reduce

One of the code examples on that page is:

 (reduce #'+ '()) =>  0

Raising an error if the ind (coll) argument is empty seems like another reasonable behavior.

@sogaiu
Copy link
Collaborator

sogaiu commented Jan 17, 2025

It looks like the current behavior is intentional.

I think it might be better to change the docstring or the behavior. Will make an issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants