Functional equivalent of decorator pattern?

In functional programming, you would wrap a given function in a new function.

To give a contrived Clojure example similar to the one quoted in your question:

My original drawing function:

(defn draw [& args]
  ; do some stuff 
  )

My function wrappers:

; Add horizontal scrollbar
(defn add-horizontal-scrollbar [draw-fn]
  (fn [& args]
    (draw-horizontal-scrollbar)
    (apply draw-fn args)))


; Add vertical scrollbar
(defn add-vertical-scrollbar [draw-fn]
  (fn [& args]
    (draw-vertical-scrollbar)
    (apply draw-fn args)))

; Add both scrollbars
(defn add-scrollbars [draw-fn]
  (add-vertical-scrollbar (add-horizontal-scrollbar draw-fn)))

These return a new function that can be used anywhere the original drawing function is used, but also draw the scrollbars.

Leave a Comment