您与上一个非常接近,但您需要添加约束:
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ConstraintKinds #-}
import Data.Proxy
both :: (c a, c b)
=> Proxy c
-> (forall x. c x => x -> r)
-> (a, b)
-> (r, r)
both Proxy f (x, y) = (f x, f y)
demo :: (String, String)
demo = both (Proxy :: Proxy Show) show ('a', True)
Proxy 是通过歧义检查所必需的。我认为这是因为它不知道要从函数中使用约束的哪一部分。
为了与其他情况统一,您需要允许空约束。这可能是可能的,但我不确定。您不能部分应用类型族,这可能会有点棘手。
这比我想象的要灵活一些:
demo2 :: (Char, Char)
demo2 = both (Proxy :: Proxy ((~) Char)) id ('a', 'b')
直到现在我才知道你可以部分应用类型相等,哈哈。
很遗憾,这不起作用:
demo3 :: (Int, Int)
demo3 = both (Proxy :: Proxy ((~) [a])) length ([1,2,3::Int], "hello")
对于列表的特殊情况,我们可以使用GHC.Exts 中的IsList 来使其工作(IsList 通常与OverloadedLists 扩展一起使用,但我们在这里不需要):
demo3 :: (Int, Int)
demo3 = both (Proxy :: Proxy IsList) (length . toList) ([1,2,3], "hello")
当然,最简单(甚至更通用)的解决方案是使用(a -> a') -> (b -> b') -> (a, b) -> (a', b') 类型的函数(如bimap from Data.Bifunctor 或(***) from Control.Arrow),然后给它两次相同的函数:
λ> bimap length length ([1,2,3], "hello")
(3,5)
统一问题中的所有三个示例
好的,经过更多的思考和编码,我想出了如何至少将您给出的三个示例统一到一个函数中。这可能不是最直观的事情,但它似乎有效。诀窍是,除了我们上面的内容之外,如果我们给类型系统提供以下限制,我们允许函数返回两种不同的结果类型(结果对的元素可以是不同的类型):
两种结果类型都必须与双参数类型类给出的相应输入类型有关系(我们可以将单参数类型类视为类型的逻辑谓词,我们可以查看双参数类型类作为捕获两种类型之间的二元关系)。
这对于applyToTuple (+5) (10 :: Int, 2.3 :: Float) 之类的东西是必要的,因为它会返回(Int, Float)。
这样,我们得到:
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
import Data.Proxy
import GHC.Exts
both :: (c a, c b
,p a r1 -- p is a relation between a and r1
,p b r2 -- and also a relation between b and r2
)
=> Proxy c
-> Proxy p
-> (forall r x. (c x, p x r) => x -> r) -- An input type x and a corresponding
-- result type r are valid iff the p from
-- before is a relation between x and r,
-- where x is an instance of c
-> (a, b)
-> (r1, r2)
both Proxy Proxy f (x, y) = (f x, f y)
Proxy p 表示输入和输出类型之间的关系。接下来,我们定义一个便利类(据我所知,它在任何地方都不存在):
class r ~ a => Constant a b r
instance Constant a b a -- We restrict the first and the third type argument to
-- be the same
这让我们可以在结果类型保持不变时使用both,方法是将Constant 部分应用于我们知道的类型(我也不知道您可以部分应用类型类,直到现在。我为这个答案学到了很多东西,哈哈)。例如,如果我们知道在两个结果中都是Int:
example1 :: (Int, Int)
example1 =
both (Proxy :: Proxy IsList) -- The argument must be an IsList instance
(Proxy :: Proxy (Constant Int)) -- The result type must be Int
(length . toList)
([1,2,3], "hello")
第二个测试用例也是如此:
example2 :: (String, String)
example2 =
both (Proxy :: Proxy Show) -- The argument must be a Show instance
(Proxy :: Proxy (Constant String)) -- The result type must be String
show
('a', True)
第三个是更有趣的地方:
example3 :: (Int, Float)
example3 =
both (Proxy :: Proxy Num) -- Constrain the the argument to be a Num instance
(Proxy :: Proxy (~)) -- <- Tell the type system that the result type of
-- (+5) is the same as the argument type.
(+5)
(10 :: Int, 2.3 :: Float)
我们这里的输入和输出类型之间的关系实际上只比其他两个例子稍微复杂一点:我们不是忽略关系中的第一个类型,而是说输入和输出类型必须相同(这在 @ 987654349@)。换句话说,在这种特殊情况下,我们的关系是等式关系。