Any way to print out a type of a variable in a do / while / let block?

早过忘川 提交于 2019-12-03 07:14:11

问题


Is there any way to print out the inferred type of a nested variable in ghci? Consider the code,

let f = g where
    g (x :: Int) = x

then, it'd be nice to query the type of g, e.g. :t f.g would print out Int -> Int.


回答1:


You can coax this information out by giving an appropriately wrong type annotation and checking the error message.

*Main> let f = g where g::a; g (x::Int) = x

<interactive>:1:23:
    Couldn't match type `a1' with `Int -> Int'
      `a1' is a rigid type variable bound by...



回答2:


ghci debugger can print it for you with a properly placed breakpoint (but you'll need to load your definition within a module):

{-# LANGUAGE ScopedTypeVariables #-} 

f a = g a where
    g (x :: Int) = x

Then in ghci:

Prelude> :l tmp2.hs
[1 of 1] Compiling Main             ( tmp2.hs, interpreted )
Ok, modules loaded: Main.
*Main> :b 3 9
Breakpoint 0 activated at tmp2.hs:3:7-9
*Main> f undefined
Stopped at tmp2.hs:3:7-9
_result :: Int = _
a :: Int = _
g :: Int -> Int = _
[tmp2.hs:3:7-9] *Main>


来源:https://stackoverflow.com/questions/6756721/any-way-to-print-out-a-type-of-a-variable-in-a-do-while-let-block

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!