例如,我有以下功能:
foo :: t -> f
foo var = foo' b var
where
b = bar 0.5 vect
Run Code Online (Sandbox Code Playgroud)
我需要指定文字'0.5类型 - 't'
如果我写smth.比如(0.5::t),GHC创建新的类型变量't0',它与原始't'不对应.
我写了一个小函数
ct :: v -> v -> v
ct _ u = u
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
b = bar (ct var 0.5) d
Run Code Online (Sandbox Code Playgroud)
有没有更好的解决方案?
您可以使用ScopedTypeVariables将顶级签名中的类型变量引入范围,
{-# LANGUAGE ScopedTypeVariables #-}
foo :: forall t. Fractional t => t -> f
foo var = foo' b var
where
b = bar (0.5 :: t) vect
Run Code Online (Sandbox Code Playgroud)
您的辅助函数ct- 使用翻转的参数 - 已经在Prelude中,
ct = flip asTypeOf
Run Code Online (Sandbox Code Playgroud)
所以
where
b = bar (0.5 `asTypeOf` var) vect
Run Code Online (Sandbox Code Playgroud)
也会工作.