Search code examples
functioncollectionsclojure

In clojure can you apply a function to all elements in a collection and have the return value be the input for the next?


Say you have a collection like this ({A: 1 B: 2} {A: 2 B: 5} {A: 4 B: 7}) with an unspecified amount of {A: B:} parts and a function (func arg1 arg2).

If we assume there is some initial state state and that every call to func generates a new-state. Is it possible to construct something that acts like this?

(->(func state {A: 1 B: 2})
(func {A: 2 B: 5}) 
(func {A: 4 B: 7}))

Basically the first argument is the new state and the second is the next {A: B:} from the collection.

Any help would be appreciated!


Solution

  • Yes, this function is called reduce:

    (reduce
      func
      initial-state
      input-sequence)
    

    or a version where the first element of the input sequence is used as initial state (check the function doc to see the details of its behaviour):

    (reduce 
      func
      input-sequence)
    

    For example:

    (reduce
      +
      100
      [1 2 3 4 5])
    ;; => 115
    
    (reduce
      +
      [1 2 3 4 5])
    ;; => 15