3 ms·
This is a neat trick that pops up from time to time. Instead of representing an algebraic data type as a bunch of cases that you can test with if-statements at
by ufo 13y ago
This is a neat trick that pops up from time to time. Instead of representing an algebraic data type as a bunch of cases that you can test with if-statements at runtime, you represent it as a pattern-matching function that receives a code block to run for each possibility.
https://en.wikipedia.org/wiki/Smalltalk#Control_structures https://en.wikipedia.org/wiki/Smalltalk#Control_structures
http://c2.com/cgi/wiki?VisitorPattern http://c2.com/cgi/wiki?VisitorPattern
https://en.wikipedia.org/wiki/Mogensen%E2%80%93Scott_encoding https://en.wikipedia.org/wiki/Mogensen%E2%80%93Scott_encodin...
One neat example of this correspondence is continuation-passing style. For example, in Javascript:
function foo(){ return value; }
function fooCps(cb){ cb(value); }
function bar(){
if(x){
return {tag:'OK', value:value};
}else{
return {tag:'ERROR', errmsg:"message"};
}
}
function barCps(okCb, errCb){
if(x){
okCb(value);
}else{
errCb("message");
}
}