How to use a proxy?

Why is this code not working?

class Foo a where 
    foo :: Proxy a -> Int

bar :: Foo a => a -> Int
bar _ = foo (Proxy :: Proxy a)

Unable to compile message:

Could not deduce (Foo a0) arising from a use of `foo'
from the context (Foo a)
  bound by the type signature for bar :: Foo a => a -> Int
The type variable `a0' is ambiguous
In the expression: foo (Proxy :: Proxy a)
In an equation for `bar': bar _ = foo (Proxy :: Proxy a)

I tried it with and without ScopedTypeVariables extension

+4
source share
1 answer

You need ScopedTypeVariables, and forallan introduction to get the type of the variable region:

{-# LANGUAGE ScopedTypeVariables #-}

bar :: forall a. Foo a => a -> Int
bar _ = foo (Proxy :: Proxy a)
+11
source

All Articles