Haskell类型中波形符的含义(类型相等)

AJF*_*mar 12 haskell types tilde

我一直在搞乱这个fix功能,我碰巧遇到了这个问题:

? let fix f = let x = f x in x
? fix (+)

<interactive>:15:5:
    Occurs check: cannot construct the infinite type: t ~ t -> t
    Expected type: t -> t
      Actual type: t -> t -> t
    Relevant bindings include it :: t (bound at <interactive>:15:1)
    In the first argument of ‘fix’, namely ‘(+)’
    In the expression: fix (+)
Run Code Online (Sandbox Code Playgroud)

我完全知道为什么会出现这个错误,但我注意到那里有一个有趣的签名:t ~ t -> t.这种类型意味着什么?什么代字号在haskell中的类型签名中意味着什么?他们在哪里使用?

Sho*_*hoe 16

~该错误中的Tilde()表示类型相等.它在告诉你它不能推断tt -> t.该符号也用于无可辩驳的模式,但这是一个完全不同的上下文.

  • @AJFarmar的`TypeFamilies`扩展允许你在自己​​的类型签名中使用`~`来表示类型相等,就像在这个错误消息中使用它一样.这是你在使用类型同义词系列时你想要的东西,但是它可以自己用于做各种类型级别的技巧(我头脑中的一个例子:你可以得到一个类的"默认"实例)使用`实例Foo X`和`instance(y~Y)=> Foo y`重叠实例` (9认同)