[Haskell-cafe] Matching constructors
Cale Gibbard
cgibbard at gmail.com
Fri Feb 10 21:29:01 EST 2006
On 10/02/06, Creighton Hogg <wchogg at primula.hep.wisc.edu> wrote:
> Hi,
> If I have something like
> data Patootie = Pa Int | Tootie Int
> and I want to pull out the indices of all elements of a list
> that have type constructor Tootie, how would I do that?
>
> I thought I might be able to use findIndices, but I don't
> know how to express the predicate.
Just to clear up a small point, Tootie isn't a type constructor, but a
data constructor. ('Maybe' is a type constructor, 'Just' is a data
constructor.)
You can use list comprehensions with pattern matching to write this
fairly succinctly:
tootieIndices xs = [i | (Tootie {}, i) <- zip xs [0..]]
The {} matches whatever parameters Tootie might have, so this will
continue to work even if you later extend the Tootie data constructor
with more fields. If you want to match more carefully, you can of
course put a variable there.
- Cale
More information about the Haskell-Cafe
mailing list