23 Aug 2013 11:23

## typeclass constraints

```Hi everybody,

There is something I do not understand in the way typeclass constraints are
inferred.

1/ Take the following function definition:

sum' [] = []
sum' (x:xs) = x + sum' xs

GHCI correctly gives:

> :t sum'
sum' :: Num [a] => [[a]] -> [a]

So it has inferred that the type list has to be an instance of Num for sum'
to be able to work. It will give an error if we try to use sum' without
implementing the instance.

2/ Now, take the following definition:

------------------------

p :: a -> ExpQ
p n = [| show n |]
------------------------
```

23 Aug 2013 11:36

### Re: typeclass constraints

```On 23 August 2013 19:23, TP <paratribulations <at> free.fr> wrote:
> Hi everybody,
>
>
> There is something I do not understand in the way typeclass constraints are
> inferred.
>
>
> 1/ Take the following function definition:
>
> sum' [] = []
> sum' (x:xs) = x + sum' xs

You haven't specified a type signature here, so GHC will derive the
most generic one possible.

>
> GHCI correctly gives:
>
>> :t sum'
> sum' :: Num [a] => [[a]] -> [a]
>
> So it has inferred that the type list has to be an instance of Num for sum'
> to be able to work. It will give an error if we try to use sum' without
> implementing the instance.
>
>
> 2/ Now, take the following definition:
>
> ------------------------
```

23 Aug 2013 11:36

### Re: typeclass constraints

```Hi TP,

The difference is that in your second example, you have specified the
type signature

p :: a -> ExpQ

so GHC checks whether p has this type, and correctly objects that it
doesn't. If you leave off the type signature, as you did for sum', the
right thing will be inferred.

Hope this helps,

On 23/08/13 10:23, TP wrote:
> Hi everybody,
>
>
> There is something I do not understand in the way typeclass constraints are
> inferred.
>
>
> 1/ Take the following function definition:
>
> sum' [] = []
> sum' (x:xs) = x + sum' xs
>
> GHCI correctly gives:
>
```

23 Aug 2013 11:44

### Re: typeclass constraints

```Adam Gundry wrote:

> If you leave off the type signature, as you did for sum', the
> right thing will be inferred.

Thanks Adam and Ivan. Very stupid question...

TP
```

Gmane