Haskell: 打印函数内变量的类型

Haskell: Print type of variable within function

如何在 .hs 文件中打印函数内变量的类型?

从ghci,我可以做到:type var。我该如何执行以下操作:

sumList :: [Int] -> Int
sumList [] = 0
sumList (h:t) = traceShow (type h) $ h : sumList t

哪个会在每次递归迭代时打印类似 h::Int 的内容?

您可以使用 typeOf :: forall a. Typeable a => a -> TypeRep 作为 Typeable 类型类实例的所有类型:

import Data.Typeable(<b>typeOf</b>)

sumList :: [Int] -> Int
sumList = foldr (\h -> traceShow (<b>typeOf</b> h) (h+)) 0

当然,对于给定的 sumList 函数,它总是 return Int,因为这是列表中项目的类型。

因为 Haskell 有完整的 类型擦除 没有像 Java 的 instanceof 这样的东西可以确定对运行时类型:由于编译器在编译时知道所有必要的类型,因此不会使用相应类型“标记”对象。