Skip to content

Instantly share code, notes, and snippets.

@saolsen
Last active December 15, 2015 18:39
Show Gist options
  • Save saolsen/5305308 to your computer and use it in GitHub Desktop.
Save saolsen/5305308 to your computer and use it in GitHub Desktop.
reduce!
(defn reducer
;; Removes 5 and the item after it from a sequence.
[{:keys [flag seq]} item]
(cond
flag {:flag false :seq seq}
(= item 5) {:flag true :seq seq}
:else {:flag false :seq (conj seq item)}))
(:seq (reduce reducer {:flag false :seq []} [1 2 3 4 5 6 7 8 9 10]))
@saolsen
Copy link
Author

saolsen commented Apr 3, 2013

In just about any other functional language you'd use a tuple instead of a map. Maps make what the two values are more explicit though so I like them more.

(defn reducer
  ;; Removes 5 and the item after it from a sequence.
  [[flag seq] item]
  (cond
   flag       [false seq]
   (= item 5) [true seq]
   :else      [false (conj seq item)]))

(:seq (reduce reducer [false []] [1 2 3 4 5 6 7 8 9 10]))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment