Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Filter set based on member type?

Let's say I have the following data structure in Haskell to represent a Checkers /Draughts piece:

data Piece = Reg {pos :: Square, color :: Color}
         | King {pos :: Square, color :: Color}
    deriving (Show, Eq)

Given a list of these Pieces, how might I isolate the Kings from the list? I've been looking 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 something that seemed obvious to me.

In short, I need a method that will, given a Data.Set set of Piece, return the subset of all King type pieces. I feel like it's something very simple but that I haven't encountered yet because I'm new to the Data.Set class in Haskell.

like image 983
Govind Parmar Avatar asked May 21 '26 14:05

Govind Parmar


1 Answers

You can define a Boolean function isKing and then use filter in Data.Set, as follows:

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
like image 141
thor Avatar answered May 23 '26 06:05

thor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!