Are ecclesiastical types of sums a suitable alternative in untyped language?

I've been wrestling with the idea of ​​a sum type in Javascript for quite some time. The language contains neither native sum types nor pattern matching. While you can mimic the types of sums with plain old Javascript Object

and a prototype system and introduce a primitive form of pattern matching (duck typing and branching through switch

), the approach is tedious and the result doesn't look like idiomatic - at least in mine sight.

So, I came up with the idea of ​​using the church encoding to express the types of sums - however, not in a strict order, that is, such language features as the conditional operator, etc. I implemented the option type as an exercise:

const some = a => _ => f => f(a);
const none =      x => _ => x

const head = xs => 0 in xs ? some(xs[0]) : none;

head(["foo"]) ("") (x => x.toUpperCase()); // "FOO"
head([]) ("") (x => x.toUpperCase()); // ""

      

First of all, I'm not sure if this is the correct implementation. Apart from this, I am concerned about two things:

  • I'm not sure if there is an appropriate default for all possible scenarios. ""

    is a neutral element for String

    - but is there such an element as neutral or null for any type?
  • since head

    now returns a binary function, it is no longer linked

Also, I find this approach very promising as it relies solely on higher-order functions and doesn't introduce fancy new types that are somehow foreign to the language.

Is Chruch coding just a good intellectual challenge, or is it a technique that can solve real-world problems?

Sorry if this question is too broad or confusing or both, but I feel stumped.

+3


source to share


1 answer


First, in Smalltalk, with its "really everything is an object", logic and conditionals are not language constructs, they are represented by boolean (although no one calls them that, I guess). Smalltalk boolean is an object that accepts two messages (aka "having two methods") ifTrue:

and ifFalse:

that are then processed depending on which one true

or the false

object actually is.



Also, there is a JS library called daggy with tagged sums, which internally uses something like a church encoding: it encodes the types of sums as something he calls catamorphisms , which are really just functions for choosing the right tag, although there is a bit more about this regarding the JS specs.

+1


source







All Articles