type of pattern matching

What if I want to check if a variable uses a particular constructor, but I don't want to unpack it. For example: data Item = Note Int Float Rational [Int] [Float] | Dynamic Int And I want to write doSomething :: Maybe Result doSomething item = case item of note@(Note _ _ _ _ _) -> Just $ process note _ -> Nothing But I don't like writing "Note _ _ _ _ _" Thanks, Mike

Hi Michael Untested - maybe you can use Record puns (section 7.3.15.of the GHC manual). Though they might only work if you have used field names in your data type. {} swaps for _ _ _ _ _ _ so it would be:
doSomething :: Maybe Result doSomething item = case item of note@(Note {}) -> Just $ process note _ -> Nothing

On Wed, Jul 07, 2010 at 08:26:50AM +0100, Stephen Tetley wrote:
Hi Michael
Untested - maybe you can use Record puns (section 7.3.15.of the GHC manual). Though they might only work if you have used field names in your data type.
{} swaps for _ _ _ _ _ _ so it would be:
doSomething :: Maybe Result doSomething item = case item of note@(Note {}) -> Just $ process note _ -> Nothing
Nope, this works in general, whether you've used field names or not. I use this trick all the time. Also, I see no reason to use a case; why not just doSomething item@(Note{}) = Just $ process item doSomething _ = Nothing -Brent

On Wed, Jul 7, 2010 at 9:19 AM, Michael Mossey
doSomething :: Maybe Result doSomething item = case item of note@(Note _ _ _ _ _) -> Just $ process note _ -> Nothing
But I don't like writing "Note _ _ _ _ _"
isNote (Note _ _ _ _ _) = True isNote _ = False doSomething :: Maybe Result doSomething item | isNote item = Just $ process note | otherwise = Nothing But I don't like writing "Note _ _ _ _ _"

David Virebayre wrote:
On Wed, Jul 7, 2010 at 9:19 AM, Michael Mossey
wrote: doSomething :: Maybe Result doSomething item = case item of note@(Note _ _ _ _ _) -> Just $ process note _ -> Nothing
But I don't like writing "Note _ _ _ _ _"
isNote (Note _ _ _ _ _) = True isNote _ = False
doSomething :: Maybe Result doSomething item | isNote item = Just $ process note | otherwise = Nothing
But I don't like writing "Note _ _ _ _ _"
I think this is pretty good because I can use isNote with a filter in another function. Thanks, Mike
participants (4)
-
Brent Yorgey
-
David Virebayre
-
Michael Mossey
-
Stephen Tetley