有没有办法让 GHC 提供类型化孔的类型约束?

目前的行为

Prelude> show _


<interactive>:7:6:
Found hole ‘_’ with type: a0
Where: ‘a0’ is an ambiguous type variable
Relevant bindings include it :: String (bound at <interactive>:7:1)
In the first argument of ‘show’, namely ‘_’
In the expression: show _
In an equation for ‘it’: it = show _

想要的行为

如果 GHC 也能告诉我类型化的空洞具有 Show类型的类约束,那就太好了。

Misc

GHC 版本7.8.1

2001 次浏览

No currently its not possible.But it may be added to GHC as per the speculations.

This is now fixed in GHC 8.0 thanks to @DominiqueDevriese's GHC ticket.

Due to extended type defaulting, this isn't immediately obvious in GHCi. With your example,

> show _


<interactive>:7:6: error:
• Found hole: _h :: ()
Or perhaps ‘_h’ is mis-spelled, or not in scope
• In the first argument of ‘show’, namely ‘_h’
In the expression: show _h
In an equation for ‘it’: it = show _h
• Relevant bindings include
it :: String (bound at <interactive>:7:1)

the type of the hole is defaulted to (). This is apparently the desired behavior, though there's an argument to be made that extended defaulting shouldn't apply to holes (as a common use for them is to get the compiler to tell you the inferred type).

Nevertheless, if you compile with GHC or disable extended default rules in GHCi (via :set -XNoExtendedDefaultRules), we see the result of the improvements:

<interactive>:3:1: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘show’
prevents the constraint ‘(Show a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance Show Ordering -- Defined in ‘GHC.Show’
instance Show Integer -- Defined in ‘GHC.Show’
instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’
...plus 22 others
...plus 11 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the expression: show _
In an equation for ‘it’: it = show _


<interactive>:3:6: error:
• Found hole: _ :: a0
Where: ‘a0’ is an ambiguous type variable
• In the first argument of ‘show’, namely ‘_’
In the expression: show _
In an equation for ‘it’: it = show _
• Relevant bindings include
it :: String (bound at <interactive>:3:1)

Try it :: _ => _ in GHC 8.8+.