[Haskell-cafe] local type denotation

Richard O'Keefe ok at cs.otago.ac.nz
Wed Nov 14 23:13:56 CET 2012


On 15/11/2012, at 1:03 AM, Serge D. Mechveliani wrote:

> Please,
> how to correctly set an explicit type for a local value in the body of 
> a polymorphic function?

Other people have told you how to do it.
I'd like to tell you why you don't need to.

> 
> Example (tested under  ghc-7.6.1):
> 
>  data D a = D1 a | D2 a (a -> a)
> 
>  f :: Eq a => D a -> a
>  f (D1 x)   = x
>  f (D2 x g) = let -- y :: Eq a => a
>                   y = g x
>               in  if x == y then x else g y

You say that you want y to have exactly the type a.
Look around.  Is there some data in scope with that type?
Yes: (D2 x g) :: a => x :: a.
So you just want to say "y has the same type as x".

There's a Prelude function

	asTypeOf :: a -> a -> a
	asTypeOf x y = x

So e1 `asTypeOf` e2 gives you the value of e1,
having first ensured that e1 and e2 have the same type.

So

f :: Eq a => D a -> a
f (D1 x)   = x
f (D2 x g) = if x == y then x else g y
             where y = g x `asTypeOf` x

You apparently already know that you don't need any of this
(thanks to x == y), but want to be explicit.  The question
is how explicit you want to be.  Using asTypeOf is sort of
half way between implicit typing and showing the type you
want _as_ a type.
> 
The other question, I suppose, is _why_ you want to be explicit?




More information about the Haskell-Cafe mailing list