[Haskell-cafe] Functors and the Visitor Pattern

Edward Kmett ekmett at gmail.com
Wed Jun 3 11:26:46 EDT 2009

The concepts are fairly closely related but each entails something the other
does not. Functor entails parametric polymorphism with respect to the
contents of the container. And a visitor can extract a result from the

As a result you may want to think in terms of a Traversable or Foldable
functor rather than just a Functor. These will let you extract a monadic or
applicative result from your container.

Now, as for your actual question, Applicative functors are really hard to
model in other languages. With C++ templates you can probably get a weak
approximation with something like the encoding used here, possibly mixed
with some boost magic for a usable function type:


But I can't think of anyone that would try to use it in production code,
and there are many common idioms that that style of translation can't
account for (i.e. polymorphic recursion).

-Edward Kmett

On Wed, Jun 3, 2009 at 9:10 AM, Tom.Amundsen <tomamundsen at gmail.com> wrote:

> So, last night, I was having this problem with my Java code where I
> couldn't
> figure out for the life of me how to write a piece of code without a big if
> {} else if {} else if {} ... else {} structure. I was Googling "Java
> Reflection" to try to determine how to "cast to the most concerete subclass
> at runtime." Then it dawned on me that what I was trying to do has already
> been solved by using the Visitor design pattern.
> Then, after reading the Visitor design pattern page on Wiki, it said that
> the visitor pattern is essentially an implementation of a functor. Aha! It
> totally clicked. The Visitor pattern allows you to collect code for similar
> operations, while spreading apart code for similar objects. Now that really
> sounds like a functor!
> Although, now I'm second guessing myself, because I can't figure out how we
> could create some design pattern that simulates an applicative functor. I'm
> pretty sure the Visitor pattern doesn't take you this far (but I am willing
> to be corrected). So, is there a way to create applicative functors in
> non-functional languages? What would that pattern look like?
> - Tom
> --
> View this message in context:
> http://www.nabble.com/Functors-and-the-Visitor-Pattern-tp23851113p23851113.html
> Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090603/62d999ae/attachment.html

More information about the Haskell-Cafe mailing list