← Back to context

Comment by Joker_vD

11 hours ago

Just use Scott-Mogensen encoding, seriously.

    Zero = z. s. z
    Succ = n. z. s. s n

    isZero = n. n True (_. False)
    pred   = n. n Zero (r. r)

Addition requires explicit recursion, however (since numbers aren't folds), so I guess you'll have to either use Y combinator or closure-convert manually:

    add' = add'. m. n. m n (r. Succ (add' add' r n))
    add = add' add'

In any case, arithmetic operations can't be made fully constant-time for obvious reasons so whether your prefer this to Church numerals is a matter of taste. However, for lists/tuples the ability to execute head/tail/cons in constant time is much more important in practice than being able to do append in constant time.

> Scott-Mogensen encoding

just Scott encoding, Scott-Mogensen refers to a meta encoding of LC in LC. Scott's encoding is fine but requires fixpoint recursion for many operations as you said.

Interestingly though, Mogensen's ternary encoding [1] does not require fixpoint recursion and is the most efficient (wrt being compact) encoding in LC known right now.

> Just use [..], seriously

do you have any further arguments for Scott's encoding? There are many number encodings with constant time predecessor, and with any number requiring O(n) space and `add` being this complex, it becomes quite hard to like

[1]: https://dl.acm.org/doi/10.5555/646802.705958