Haskell: set of filters based on member type?
Let's say I have the following data structure in Haskell to represent Checkers / Draft:
data Piece = Reg {pos :: Square, color :: Color}
| King {pos :: Square, color :: Color}
deriving (Show, Eq)
Given a list of these Pieces
, how can I single out King
from the list? I looked at the documentation for Data.Set
at http://www.haskell.org/ghc/docs/7.6.2/html/libraries/containers-0.5.0.0/Data-Set.html but couldn't find what seemed obvious to me.
In short, I need a method that, if given a Data.Set
set Piece
, returns a subset of all fragments of a type King
. I feel like this is something very simple, but I haven't met yet because I'm new to the Data.Set class in Haskell.
source to share
You can define a boolean function isKing
and then use filter
in Data.Set
as shown below:
import Data.Set as S
data Color = Int deriving (Show, Eq)
data Square = Square (Int,Int) deriving (Show, Eq)
data Piece = Reg {pos :: Square, color :: Color}
| King {pos :: Square, color :: Color}
deriving (Show, Eq)
isKing King{} = True
isKing _ = False
getKings s = S.filter isKing s
source to share