简体   繁体   English

(Purescript)如何在代数数据类型上模式匹配“空类型”

[英](Purescript) How do I pattern match on an algebraic data type that is the “empty type”

I'm working with the following algebraic data type in PureScript... 我正在使用PureScript中的以下代数数据类型...

data Extended a = Infinite | Finite a

v1 = Finite 11
v2 = Infinite

I'm having trouble figuring out how to pattern match the "Infinite" case, since it appears that v2 has type forall t140. Extended t140 我无法弄清楚如何模式匹配“无限”情况,因为看起来v2类型为forall t140. Extended t140 forall t140. Extended t140 . forall t140. Extended t140 I'm assuming t140 is some sort of placeholder the compiler automatically fills in. The type of v1 is Extended Int . 我假设t140是编译器自动填充的某种占位符.v1的类型是Extended Int So if I setup an instance of Eq to compare values of Extended, the Infinite case does not match... 因此,如果我设置一个Eq实例来比较Extended的值,那么Infinite案例就不匹配......

instance extendedEq :: (Eq a) => Eq (Extended a) where
  eq (Finite a) (Finite b) = eq a b
  eq Infinite Infinite = true
  eq Infinite _ = false
  eq _ Infinite = false

So when I try and run v2 == v2 I get the error... 所以,当我尝试运行v2 == v2我收到错误...

No type class instance was found for Prelude.Eq (Extended _0)

Which makes sense, since I imagine it's trying to find an Eq instance for t140. 这是有道理的,因为我想它正试图为t140找到一个Eq实例。

So my question is, how can I pattern matching on the Infinite type? 所以我的问题是,如何在无限类型上进行模式匹配?

The problem is not about pattern matching or your instance implementation. 问题不在于模式匹配或您的实例实现。 Your ADT has the same structure as Maybe , and if I try 您的ADT与Maybe具有相同的结构,如果我尝试的话

main = print (Nothing == Nothing)

I get the error code: https://github.com/purescript/purescript/wiki/Error-Code-NoInstanceFound 我收到错误代码: https//github.com/purescript/purescript/wiki/Error-Code-NoInstanceFound

Your type parameter t140 could be anything in the Eq type class, so the compiler is not able to select an instance. 您的类型参数t140可以是Eq类型类中的任何内容,因此编译器无法选择实例。 You need to add a type annotation to at least one of the operands of == : 您需要在==至少一个操作数中添加类型注释:

v2 = Infinite :: Extended Int

But I admit it would be more satisfactory if the compiler could figure out that Infinite == Infinite for any (same) type parameter... 但我承认,如果编译器能够找出任何(相同)类型参数的Infinite == Infinite ,那将会更令人满意......

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

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