[Haskell-beginners] understanding type classes and class constraints
Dan Krol
orblivion at gmail.com
Mon Nov 18 00:54:45 UTC 2013
When you run "test Nothing", ghc doesn't know what type Nothing is. Just 0,
ghc can deduce is a Maybe Integer. Nothing can be Maybe Integer, Maybe
(Maybe Integer), Maybe Char, etc.
Try running:
test (Nothing :: Maybe Integer)
On Sun, Nov 17, 2013 at 4:47 PM, Robert Krahn <robert.krahn at gmail.com>wrote:
> Hi everyone,
>
> I'm currently enjoying to learn Haskell and came upon a problem I don't
> understand:
>
> Motivated by the Learn you a Haskell / yes-no typeclass example I tried to
> create a simple "Tester" type class:
>
> class Tester a where
> test :: a -> Bool
>
> I wasn't to define the rules when test returns True/False for various
> types, e.g.
>
> instance Tester Integer where
> test 0 = False
> test _ = True
>
> For the Maybe instance I want to delegate to the value of Just and add a
> class constraint:
>
> instance (Tester m) => Tester (Maybe m) where
> test Nothing = False
> test (Just x) = test x
>
> It compiles nicely and works for Just values
> test (Just 3) -- True
> test (Just 0) -- False
>
> But
> test Nothing
>
> gives me
> No instance for (Tester a0) arising from a use of `test'
> The type variable `a0' is ambiguous
> Possible fix: add a type signature that fixes these type variable(s)
> Note: there are several potential instances:
> instance Tester m => Tester (Maybe m)
> instance Tester Integer
> In the expression: test Nothing
>
> Could you please enlighten me what's going on and how to fix my code?
>
> Thank you!
> Robert
>
> _______________________________________________
> 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/20131117/887c8469/attachment.html>
More information about the Beginners
mailing list