[Haskell-beginners] Collapsing multiple case branches?

Colin Paul Adams colin at colina.demon.co.uk
Sat Jan 3 15:11:44 EST 2009

>>>>> "Thomas" == Thomas Davie <tom.davie at gmail.com> writes:

    Thomas> Hi Colin, northernRange :: PieceType > Int -- note the
    Thomas> camel case, that's traditional in Haskell circles

I know, but I find it vile.

    Thomas> northernRange p | p `elem` [Lance, ReverseChariot,
    Thomas> VerticalMover ....] = 11 | p `elem` [Bishop, Kylin,....] =
    Thomas> 0 | otherwise = 1

    Thomas> These are called "pattern guards" – you can put any
    Thomas> boolean expression in them.

Ah, thanks, that will do nicely.

    Thomas> Of note, if you provide an Enum instance for PieceType you
    Thomas> may really be able to do this:

    Thomas> northernRange p | p `elem` [Lance..SoaringEagle] = 11 | p
    Thomas> `elem` [Bishop..HornedFalcon] = 0 | otherwise = 1

I thought of that, but there are additional functions to do where the
required ordering would be different.

    Thomas> Finally, my guess is that you probably want a much more
    Thomas> general type for PieceType that doesn't need extended
    Thomas> every time you add a Piece to your game (and similarly
    Thomas> doesn't need every function in your program extended at
    Thomas> the same time).  Perhaps something like this:

    Thomas> data Piece = Piece { name :: String, northernRange ::
    Thomas> Int }

A reasonable guess, but as the pieces types are fixed (it's an ancient
game) I preferred to write it this way.

BTW is this (as it looks to me) a classic space-time trade-off?
Colin Adams
Preston Lancashire

More information about the Beginners mailing list