Eigenstate: myrddin-dev mailing list

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Traits seem to be working.


Go me. I was too lazy to announce this when I got it working, but I realized
last night that I should really send out a mail.

As of a few weeks ago, I got traits working -- You can now define traits
for types, and expect them to actually compile and run. Traits are close
to concepts in C++, and similar to compile time only interfaces in certain
other languages. An example would be:

    /*
    Define a hashable trait. This will allow any type that
    has an implementation of this trait to get hashed.
    */
    trait hashable @a =
        hash : (val : @a -> uint32)
    ;;

    /* hashing implementation for integers */
    impl hash int =
        hash = {val
            -> val * Bigprime
        }
    ;;

    /* hashing implementation for strings */
    impl hash byte[:] =
        hash = {str
            var h = 1
            for b in str
                h = 33 * h * (b castto(int32))
            ;;
        }
    ;;

    /* use the hashing */
    const main = {
        std.put("hash of 123: %i\n", hash(123))
        std.put("hash of "abc": %i\n", hash("abc"))
        /* this will error out, saying there's no trait implemented */
        /* std.put("hash of 'c': \n", hash('c')) */
    }


There are currently a few limitations on traits that I would like to
lift. The biggest one is that currently, it only works on concrete types.
You can't, for example, implement:

     impl hash @a::(numeric,integral) = ... ;;

and get a hash implementation for every numeric type.

This feature probably means that the API of some libraries could probably
be adjusted.

Follow-Ups:
Re: Traits seem to be working.Ryan Gonzalez <rymg19@xxxxxxxxx>
Re: Traits seem to be working.Ryan Gonzalez <rymg19@xxxxxxxxx>