swe*_*123 1 haskell functional-programming ghc ghci
如何在 .hs 文件中的函数中打印变量的类型?
从ghci,我可以做到:type var。我该如何做类似以下的事情:
sumList :: [Int] -> Int
sumList [] = 0
sumList (h:t) = traceShow (type h) $ h : sumList t
Run Code Online (Sandbox Code Playgroud)
哪个会在每次递归迭代时打印类似 h::Int 的内容?
您可以使用typeOf :: forall a. Typeable a => a -> TypeRep作为类型Typeable类实例的所有类型:
import Data.Typeable(typeOf)
sumList :: [Int] -> Int
sumList = foldr (\h -> traceShow (typeOf h) (h+)) 0Run Code Online (Sandbox Code Playgroud)
当然,对于给定的sumList函数,它总是会返回Int,因为这是列表中项目的类型。
由于 Haskell 具有完整的类型擦除,因此没有像 Java 这样的东西instanceof可以在运行时确定对类型的引用:由于编译器在编译时知道所有必需的类型,因此不会用相应的类型“标记”对象。
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |