Skip to content

Safer Types #14

@profbrandon

Description

@profbrandon

It might be nice to wrap data in an object that contains some type information. In essence, the only function which would know about this layer would be the constructors and destructors. For example, lists might look like this:

const getFullType = (name, container, dataType) => 
    name + (container ? '(' + dataType.fullName + ')' : '')

const typeInfo = (name, container, dataType) => Object.freeze({
    __proto__: null,

    name:      name,
    container: container,
    dataType:  dataType,
    fullName:  getFullType(name, container, dataType)
})

const wrapType = (typeInfo, data) => Object.freeze({
    __proto__: null,

    info: typeInfo,
    data: data
})

const expectType = (typeName, value) => compute => {
    if (value.info.name !== typeName)
        throw TypeError...
    else
        return compute();
}
...

const listInfo = dataType => typeInfo('List', true, dataType);

const listWrapper = listDataType => listData => wrapType(listInfo(listDataType), listData); 

const empty = listWrapper(undefined, Object.freeze({
    __proto__: null,

    head: undefined,
    tail: undefined
}))

const cons = (a, as) => expectType('List', as)(
    () => expectType(as.info.name, a)(
        () => {
            if (getFullType(a.info.dataType) != getFullType(as.info.dataType))
                throw TypeError...
            else
                return wrapType(as.info, Object.freeze({
                    __proto__: null,

                    head: a,
                    tail: as.data
                })
        })
);

const isEmpty = as => expectType('List', as)(() => as.data.head == undefined);

const foldr_unchecked = (seed, ax) => as => {
    if (as.data.head == undefined)
        return seed;
    else
        return ax(as.data.head, foldr_unchecked(seed, ax)(as.data.tail));
}

const foldr = (seed, ax) => as => expectType('List', as)(() => foldr(seed, ax)(as));

Whether this should be used should depend upon the speed. Perhaps it might be useful to use one of these libraries for testing and an 'untyped' one for production.

Metadata

Metadata

Assignees

No one assigned

    Labels

    improvementImprove a preexisting feature

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions