Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting the number of elements a data constructor can have

Tags:

haskell

I am writing an ADT in Haskell which represents a hand of cards. My problem is that I would like to restrict the number of (Suit,Face) which represents a card to 5 which represents a hand.

data Card = Hand [(Suit,Face)]

What I tried to do was this but it does not work.

data Card = Hand [(Suit,Face),(Suit,Face),(Suit,Face),(Suit,Face),(Suit,Face)]

My question is: how do i restrict the number of tuples to 5?

like image 859
user1850254 Avatar asked Jan 27 '13 12:01

user1850254


Video Answer


1 Answers

I'd like to add that if you use a solution based on 5-tuples (as suggested in the other answers), you can still have all folding/traversing functions you need. In particular, first define

import Control.Applicative
import Data.Foldable
import Data.Traversable

data Tuple5 a = Tuple5 a a a a a

and define folding and traversing operations on it:

instance Traversable Tuple5 where
    traverse f (Tuple5 a b c d e)
            = Tuple5 <$> f a <*> f b <*> f c <*> f d <*> f e
instance Foldable Tuple5 where
    foldMap = foldMapDefault
instance Functor Tuple5 where
    fmap    = fmapDefault

Then, you can have

data Hand = Hand (Tuple5 Card)

and fold/traverse the structure using any methods from Foldable/Traversable/Functor.


Update: Recently I created a small library tuples-homogenous-h98 that defines newtype aliases for homogenous tuples such as

newtype Tuple5 a = Tuple5 { untuple5 :: (a,a,a,a,a) }

and adds proper Traversable, Foldable, Functor, Applicative and Monad instances.

like image 107
Petr Avatar answered Sep 19 '22 11:09

Petr