Mark Cidade
Mark Cidade

Reputation: 100057

Combined type = one, the other, or both?

I'm wondering if this is possible in Haskell:

type DateTime = Date | Time | Date :+ Time

...so that it can be either a specific date, a specific time or a complex value made up of both.

Upvotes: 0

Views: 120

Answers (1)

AJF
AJF

Reputation: 11924

You just made it - of course it's possible!

Here's what I would make it:

data Both a b
    = First a
    | Second b
    | Both a b

Interestingly, this is a bifunctor:

import Data.Bifunctor

instance Bifunctor Both where
    bimap f _ (First a)  = First (f a)
    bimap _ g (Second b) = Second (g b)
    bimap f g (Both a b) = Both (f a) (g b)

As J. Abrahamson said, there is a type called These in the package Data.These, which includes Monad and Bifunctor instances, as well as some awesome typeclass instances like Bifoldable and Bitraversable that are totally worth having a peek at.

Upvotes: 5

Related Questions