繁体   English   中英

使用 Newtype 类约束纯脚本时编译器无法推断类型

[英]Compiler can't infer type while using Newtype class Constraint purescript

我试图编写一个可以获取新类型包装的数据的函数。

newtype Person = Person {name :: String, age :: Int}

getRecord :: forall r. Newtype Person r => Person -> r
getRecord (Person p) = p

这无法编译并抱怨

Could not match type

    { age :: Int
    , name :: String
    }

  with type

    r0


while checking that type { age :: Int
                         , name :: String
                         }
  is at least as general as type r0
while checking that expression p
  has type r0
in value declaration getRecord

但是当我这样做时

getRecord :: forall r. Newtype Person r => Person -> r
getRecord  = unwrap 

它工作正常! 我的问题是为什么它不能第一次推断类型?

newtype 类型类的定义如下,

class (Coercible t a) <= Newtype t a | t -> a

这意味着它可以在知道t是什么时推断出a 那为什么它第一次不起作用。

约束求解发生在调用函数时,但不是在定义函数时。

在调用站点,编译器将解决Newtype Person r约束并计算出r ~ { age :: Int, name :: String } ,因此您可以使用它的字段。

但是在定义站点,编译器不会这样做。 在那里,它只是一些未知的类型r 而且由于它是未知的,编译器不能真诚地告诉r ~ { age :: Int, name :: String } ,所以存在类型不匹配。


使用unwrap有效,因为不需要知道类型r 不管它是什么,它只是直接传递给unwrap ,你的函数不需要知道任何关于它的信息。


为什么编译器不在定义站点进行约束求解? 我的意思是它在技术上可以,但无论如何这将有点用处:毕竟,如果你已经知道类型,只需写出来:

getRecord :: Person -> { age :: Int, name :: String }
getRecord (Person p) = p

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM