What is the closest equivalent: inject ghci into the ghc source file?
A handy trick I recently discovered is to use typed holes in combination with asTypeOf
1 .
If you have code that compiles and you want to know what the type of an expression inside of it is, replacing that expression with a hole, sometimes screw things up, like in:
-- what is the type of this part, I wonder?
f xs = 3 * length xs
Replacement with length xs
reports _
:
foo.hs:1:12: Warning:
Found hole ‘_’ with type: a
Where: ‘a’ is a rigid type variable bound by
the inferred type of f :: t -> a at foo.hs:1:1
length xs
certainly not of type a
!
But if you use asTypeOf
, you can leave there length xs
and insert the hole, which should be of the same type as it is:
f xs = 3 * (length xs `asTypeOf` _)
Now we get:
foo.hs:1:34: Warning:
Found hole ‘_’ with type: Int
Much better.
1 isasTypeOf
exactly the same as const
because it returns its first argument and completely ignores its second. However, its type causes the second argument to be the same as the first; it is for writing backwindow infix.
It is intended for when you have a subexpression that is too polymorphic and GHC complains about ambiguous type variables; you can use a built-in type declaration, but sometimes this is not possible without extension ScopedTypeVariables
. If you have a different value that is correct, you can use it asTypeOf
to "select" the appropriate case from the polymorphic expression without changing the value returned by the expression.
My use of it here is "back" from the alleged case; I want the item on the left to constrain the type of the (ignored) hole on the right, not the other way around.
source to share