Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practical reasons for Church Encoding

Church encoding (aka Visitor Pattern) is a way of representing data as functions: instead of

data T = C1 F1 F2 | C2 F3 F4

you can define

data T = T (forall r. (F1 -> F2 -> r) -> (F3 -> F4 -> r) -> r)

. Although the ability to represent anything as a function is nice, I've always thought the first version was preferable because it's cleaner and it does not require language extensions (explicit forall). However, you can sometimes find church-encoded data in public libraries. What are the advantages of using that?

The examples of church encoding in public libraries:

  • Iteratee
  • Revision control monad
  • (please help me extend the list)
like image 906
Rotsor Avatar asked Mar 21 '12 14:03

Rotsor


1 Answers

This corresponds to continuation-passing style with multiple continuations, and is done for performance: the explicit construction and destruction of data is avoided, instead passing control directly based on the output of the pattern-match that would be immediately done instead. This doesn't always result in improved performance, but when it does it can be fairly significant.

Basically, you can think of it as data vs. control. If what you're doing is essentially similar to control in nature — such as the success and failure branches of a parser — then the control-based representation might well be superior. Otherwise, stick with data.

like image 157
ehird Avatar answered Oct 21 '22 01:10

ehird