[Haskell-beginners] using the joker "_" on a constructor

David McBride toad3k at gmail.com
Wed Sep 18 16:22:27 CEST 2013


It has to know the constructor in order to know the type of n.  In your
case they are both int, but in the general case they could be completely
different types and therefore you could not just use the constructors
interchangeably.

If you want to write this I would go:

data Foo = Bar Int | Foo Int
def unFoo (Bar n) = n
def unFoo (Foo n) = n

f v = if even (unFoo n) then True else False

You could also define the data type as

data Foo = Bar { unFoo :: Int } | Foo { unFoo :: Int }

As long as you make sure unFoo works for every possibility (otherwise it
would be a partial function that could throw an exception).



On Wed, Sep 18, 2013 at 10:08 AM, TP <paratribulations at free.fr> wrote:

> Hi,
>
> I have a question about pattern matching.
> Consider the following code:
>
> ------------------
> data Foo = Bar Int
>          | Foo Int
>
> f :: Foo -> Bool
> f (Foo n)
>     | even n = True
>     | odd n = False
> f (Bar n)
>     | even n = True
>     | odd n = False
>
> main = do
>
> print $ f $ Bar 1
> print $ f $ Bar 2
> print $ f $ Foo 1
> print $ f $ Foo 2
> ------------------
>
> Why is it not possible to simply write for f:
>
> f v = case v of
>     _ n | even n -> True
>     _ n | odd n -> False
>
> or
>
> f (_ n)
>     | even n = True
>     | odd n = False
>
> (in both cases we get a parse error)?
>
> Thanks,
>
> TP
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20130918/861af809/attachment.htm>


More information about the Beginners mailing list