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

foldLeft/foldRight argument order #154

Open
crusso opened this issue Feb 13, 2025 · 1 comment
Open

foldLeft/foldRight argument order #154

crusso opened this issue Feb 13, 2025 · 1 comment

Comments

@crusso
Copy link
Contributor

crusso commented Feb 13, 2025

Currently, we are specifying the following signature for foldLeft/foldRight, for all ordered collections (array is just an example):

 func foldLeft<T, A>(array : [T], base : A, combine : (A, T) -> A) : A
                                                 
 func foldRight<T, A>(array : [T], base : A, combine : (T, A) -> A) : A
                                                    

(this is the relative base/combine argument order in Haskell and SML)

Notice that the combine functions take the accumulator on the left or right, but the base arguments invariably comes first.

Should we change this to:

  func foldLeft<T, A>(array : [T], base : A, combine : (A, T) -> A) : A 
  func foldRight<T, A>(array : [T], combine : (T, A) -> A, base : A) : A   // swap base and combine
                                                                                       

(this is the relative base/combine argument order in OCaml)

Informally, this corresponds to the textual order of the unfolded operations:

foldLeft([a0,...an], b, c) = c(.... c(c(b, a0), a1) ..., an)  
foldRight([a0,a1,...,an], c, b) = c(a0, c(a1, ... c(an, b)..))

Then it is clearer that b is combined with the first or last element and it might make it easier to remember the distinction between foldLeft and foldRight.

The downside is that swapping from foldLeft to foldRight requires some (more) argument shuffling.

@rvanasa
Copy link
Collaborator

rvanasa commented Feb 19, 2025

This is a good point. I would be fine with either of these options with a very slight preference for the current argument order (base, combine), which is consistent with Rust and Scala.

It seems like there is a wide range of different orderings across mainstream languages. JS and Python use combine, base for both left/right due to the base value being optional. However the argument order is usually consistent between the left and right functions.

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

No branches or pull requests

2 participants