2

Programming language: Scheme/DrRacket

I see no difference in usage between foldr and apply

Can anyone explain how they are different? As far as I can tell you can the same thing with foldr that you can with apply. Thank you!

Boolean Autocrat
  • 347
  • 2
  • 16
  • They're only equivalent if the function is associative. – Barmar Oct 08 '19 at 19:57
  • `foldr` is like the `reduce` function in Python, `Array.prototype.reduce` in JavaScript, and `array_reduce` in PHP. – Barmar Oct 08 '19 at 19:59
  • @Barmar A lot of beginners ask how `reduce` is different from `apply` too. I don't think that comparison is necessarily so useful. – amalloy Oct 08 '19 at 20:35

1 Answers1

7

They're very different, although in some cases they may be equivalent.


(apply func '(1 2 3))

is equivalent to

(func 1 2 3)

(foldr func 0 '(1 2 3))

is equivalent to

(func (func (func 3 0) 2) 1)

In cases where the function is associative and commutative, and it allows you to provide a variable number of arguments, the results will be the same. For example

(apply + '(1 2 3)) == (foldr + 0 '(1 2 3))

But foldr can be used to combine the results of functions that just take two arguments, or use more flexible ways to combine the results.

For more information about foldr, see Map, Filter, Foldr in DrRacket/Scheme

amalloy
  • 89,153
  • 8
  • 140
  • 205
Barmar
  • 741,623
  • 53
  • 500
  • 612