【发布时间】:2015-01-11 09:15:46
【问题描述】:
我想构建一种类型来匹配任何东西,但永远不会被使用。
例子:
type Any = forall a. a
f :: (x, Any) -> (Any, y) -> (x,y)
f (x,_) (_,y) = (x,y)
这与 {-# LANGUAGE ImpredicativeTypes #-} 编译得很好,但如果我尝试
f ("hi", 2) (3, (1, 2))
我得到错误:
<interactive>:19:9:
No instance for (Num a) arising from the literal `2'
Possible fix:
add (Num a) to the context of a type expected by the context: a
In the expression: 2
In the first argument of `f', namely `("hi", 2)'
In the expression: f ("hi", 2) (3, (1, 2))
<interactive>:19:13:
No instance for (Num a) arising from the literal `3'
Possible fix:
add (Num a) to the context of a type expected by the context: a
In the expression: 3
In the second argument of `f', namely `(3, (1, 2))'
In the expression: f ("hi", 2) (3, (1, 2))
如果我只是想让 x 和 y 成为 Num,那会很好,但我打算用这个做的事情需要比那个灵活得多。我知道forall a. a 匹配所有类型,但只能传递一个永远无法计算和底部的thunk。但是,我不想研究 Any 类型。
【问题讨论】:
-
你为什么不能只使用另一个类型变量,比如
z而不是Any? -
这会变得非常脆弱,如果你永远无法将它用于任何特定的事情,我不确定你为什么想要一个存在的 Any 类型。
Data.Dynamic是处理直到运行时才知道的类型的首选方法。 -
你不能通过
2,因为它是forall a. Num a => a类型,而不是Any类型。唯一可以通过的是undefined和类似的底部。 -
我认为您需要在问题中添加有关您计划如何使用您的类型的这些详细信息,并且也许还指出您将如何生成将由您的函数过滤的数据。
-
@BT。为什么你真的想要这个?如果您为您的问题提供更多背景信息,您可能会得到一些好的建议。