Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional equivalent of decorator pattern?

What is the functional programming equivalent of the decorator design pattern?

For example, how would you write this particular example in a functional style?

like image 508
Steve Wolowitz Avatar asked Aug 15 '11 11:08

Steve Wolowitz


People also ask

Are decorators functional programming?

Definition. Decorators are wrapper functions that enhance the wrapped function. You don't change the original function behavior, instead you decorate it with new behavior, achieving extensability and composability.

What is the decorator pattern also known as?

A Decorator Pattern says that just "attach a flexible additional responsibilities to an object dynamically". In other words, The Decorator Pattern uses composition instead of inheritance to extend the functionality of an object at runtime. The Decorator Pattern is also known as Wrapper.

Are decorators functional?

By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.

Are there functional design patterns?

In a functional language one does not need design patterns because the language is likely so high level, you end up programming in concepts that eliminate design patterns all together. The main features of functional programming (FP) include functions as first-class values, currying, immutable values, etc.


1 Answers

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.

like image 75
Christian Berg Avatar answered Sep 21 '22 06:09

Christian Berg