Eigenstate : Traits Anywhere

Traits Anywhere

The Myrddin programming language allows traits to be addeed to a type at any point in the code, with very few restrictions. A type does not need to be defined by the programmer in order to have a trait added to it -- adding a trait to int is no harder than adding it to a user defined type.

This sort of flexibility allows for very easy extension of code to provide a common interface that the initial author had not initially intended.

For example, the crypto hashing libraries in Myrddin predate the functional implementation of traits, so (as of this writing) there is no trait unifying all of the hash functions behind a common API.

A short while ago, a user had started writing a command line hashing tool using these libraries, designing it such that you could select the hash function based on the command line parameters.

The solution was implementing his own hasher trait and adding it to all of the hash states:

trait hasher @a -> @hash =
    init    : (h : @a# -> void)
    fin : (h : @a# -> @hash)
    add : (h : @a#, d : byte[:] -> void)
;;

impl hasher crypto.md5 -> byte[16] =
    init = {h; crypto.md5init(h)}
    fin = {h; ->crypto.md5fin(h)}
    add = {h, d; crypto.md5add(h, d)}
;;

/* repeat for all hash traits */

generic hash = {st : @hashstate#, f : std.fd -> @hash
    /* do the hashing */
}

The fact that this wasn't done out of the box is arguably a bug in the API, but being able to add or override common functions on your own is generally useful.

Asking library authors to anticipate all potential traits that can be added to a type doesn't scale well. And asking all library authors to coordinate so that library A implements all useful traits from library B is impossible.