TP | 23 Aug 11:23 2013
Picon

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:

------------------------
{-# LANGUAGE TemplateHaskell #-}

import Language.Haskell.TH
import Language.Haskell.TH.Syntax

p :: a -> ExpQ
p n = [| show n |]
------------------------
(Continue reading)

Ivan Lazar Miljenovic | 23 Aug 11:36 2013
Picon

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:
>
> ------------------------
(Continue reading)

Adam Gundry | 23 Aug 11:36 2013
Picon
Picon

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,

Adam

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:
> 
(Continue reading)

TP | 23 Aug 11:44 2013
Picon

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