mauro3 / Traits.jl

Exploration of traits in Julia
Other
39 stars 6 forks source link

Commutative monoid #7

Open tonyhffong opened 9 years ago

tonyhffong commented 9 years ago

I'm thinking how to express a commutative monoid using this framework.

For a monoid, I can do this:

@traitdef Monoid{X} begin
    mempty( ::X ) -> X
    mappend( X, X ) -> X
end

immutable Sum{T<:Number}
    value::T
end

mempty{T<:Number}( ::Type{Sum{T}} ) = Sum{T}( zero(T) )
mappend{T<:Number}( a::Sum{T}, b::Sum{T} ) = Sum{T}(a.value+b.value)

At the interface level, a commutative monoid is indistinguishable from a regular monoid. The only difference is an assertion that the mappend function for X commutes.

An approach is to whitelist X this way:

@traitdef CommutativeMonoid{X} <: Monoid{X} begin
    @constraints begin
        X <: Sum ||
        X <: Product ||
        X <: MeanWeighted
    end
end

or via some registration function so that we can add to the whitelist when packages introduce new types. It has a touch of code smell, so I want to create this issue for comments and ideas.

mauro3 commented 9 years ago

Maybe these blogs helps, not that I follow them: http://gelisam.blogspot.ch/2013/07/the-commutative-monad.html, http://winterkoninkje.dreamwidth.org/86236.html