首页 > 解决方案 > 为什么这种类型不检查?

问题描述

class Foo t where
  foo :: t

bar :: Binary t => t -> ()
bar = undefined

repro :: (Binary t, Foo t) => Proxy t -> ()
repro _proxy =
  bar (foo :: t)

编译器抱怨:

具体来说,我很惊讶它没有看到我传递tbar,并创建了一个t0类型 var。t2更神秘,因为foo被显式地注解了 type t

标签: haskell

解决方案


默认情况下,类型变量的范围不是这种方式。t函数签名中的和t函数体中的 不一样。您的代码等效于:

repro :: (Binary t, Foo t) => Proxy t -> ()
repro _proxy =
  bar (foo :: a)

您需要启用 ScopedTypeVariables 扩展,并添加显式forall t.

{-# LANGUAGE ScopedTypeVariables #-}

repro :: forall t. (Binary t, Foo t) => Proxy t -> ()
repro _proxy =
  bar (foo :: t)

推荐阅读