# Can I “couple” two types?

**URL:** https://discourse.julialang.org/t/can-i-couple-two-types/640
**Category:** New to Julia
**Tags:** question
**Created:** [November 29, 2016, 9:53pm UTC](https://discourse.julialang.org/t/can-i-couple-two-types/640 "2016-11-29T21:53:24Z")
**Posts on this page:** 1
**Showing post:** 7

<div class="post-metadata">

### Author: ![mauro3](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mauro3/32/292_2.png) [@mauro3](https://discourse.julialang.org/u/mauro3)
#### Post date: [November 30, 2016, 8:53am UTC](https://discourse.julialang.org/t/can-i-couple-two-types/640/7 "2016-11-30T08:53:24Z")

</div>

You can use traits for this:

```julia
abstract Match
abstract NotMatch
"If the two arguments match, i.e. they can work together, then it returns Match otherwise NotMatch."
function ismatch end
ismatch(::Type{B1}, ::Type{B2}) = Match
ismatch(::Type{C1}, ::Type{C2}) = Match
ismatch(::Any, ::Any) = NotMatch # catch-all defaults to NotMatch

# Now write your function like so:
quite_general{T<:A1, S<:A2}(p::T, q::Vector{S})::T = _quite_general(ismatch(T,S), p,q) # trait-dispatch
_quite_general(::Type{Match},p,q) = ... # some logic
_quite_general{T<:A1, S<:A2}(::Type{NotMatch}, p::T, q::Vector{S}) = error("Type $T and $S don't match")

```

So for each type combination you have to specify whether they match or not with `ismatch` (but just this once). Then each function which does something according to the match, you have to split up into the trait-dispatch and the logic function. There is a new manual section about this: [julia/methods.rst at 9bad705a41ab68b54b0ded18eb3c386e187ad45a · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/blob/9bad705a41ab68b54b0ded18eb3c386e187ad45a/doc/manual/methods.rst#4-trait-based-dispatch) (not merged yet thus not well rendered) and there is the package [SimpleTraits.jl](https://github.com/mauro3/SimpleTraits.jl) which provides macro-sugar for above pattern.

---

_[View the full topic](https://discourse.julialang.org/t/can-i-couple-two-types/640)._
