Ste*_*lla 6 haskell tuples hxt
对于我使用hxt的工作,我实现了以下功能:
-- | Construction of a 8 argument arrow from a 8-ary function. Same
-- implementation as in @Control.Arrow.ArrowList.arr4@.
arr8 :: ArrowList a => (b1 -> b2 -> b3 -> b4 -> b5 -> b6 -> b7 -> b8 -> c)
-> a (b1, (b2, (b3, (b4, (b5, (b6, (b7, b8))))))) c
arr8 f = arr ( \ ~(x1, ~(x2, ~(x3, ~(x4, ~(x5, ~(x6, ~(x7, x8)))))))
-> f x1 x2 x3 x4 x5 x6 x7 x8 )
Run Code Online (Sandbox Code Playgroud)
正如在haddock注释中提到的,上面的函数arr8采用8-ary函数并返回8参数箭头.我使用这样的功能:(x1 &&& x2 &&& ... x8) >>> arr8 f借此x1来x8的箭.
我的问题:有没有办法避免大元组定义?是否有更优雅的实施arr8?
这有效,虽然它取决于一些非常深刻和脆弱的类型类魔法.它还要求我们将元组结构更改为更加规则.特别是,它应该是一个类型级链表宁愿(a, (b, (c, ())))到(a, (b, c)).
{-# LANGUAGE TypeFamilies #-}
import Control.Arrow
-- We need to be able to refer to functions presented as tuples, generically.
-- This is not possible in any straightforward method, so we introduce a type
-- family which recursively computes the desired function type. In particular,
-- we can see that
--
-- Fun (a, (b, ())) r ~ a -> b -> r
type family Fun h r :: *
type instance Fun () r = r
type instance Fun (a, h) r = a -> Fun h r
-- Then, given our newfound function specification syntax we're now in
-- the proper form to give a recursive typeclass definition of what we're
-- after.
class Zup tup where
zup :: Fun tup r -> tup -> r
instance Zup () where
zup r () = r
-- Note that this recursive instance is simple enough to not require
-- UndecidableInstances, but normally techniques like this do. That isn't
-- a terrible thing, but if UI is used it's up to the author of the typeclass
-- and its instances to ensure that typechecking terminates.
instance Zup b => Zup (a, b) where
zup f ~(a, b) = zup (f a) b
arrTup :: (Arrow a, Zup b) => Fun b c -> a b c
arrTup = arr . zup
Run Code Online (Sandbox Code Playgroud)
现在我们可以做到
> zup (+) (1, (2, ()))
3
> :t arrTup (+)
arrTup (+)
:: (Num a1, Arrow a, Zup b n, Fun n b c ~ (a1 -> a1 -> a1)) =>
a b c
> arrTup (+) (1, (2, ()))
3
Run Code Online (Sandbox Code Playgroud)
如果你想定义特定的变体,它们都是正确的arrTup.
arr8
:: Arrow arr
=> (a -> b -> c -> d -> e -> f -> g -> h -> r)
-> arr (a, (b, (c, (d, (e, (f, (g, (h, ())))))))) r
arr8 = arrTup
Run Code Online (Sandbox Code Playgroud)
最后值得注意的是,如果我们定义一个懒惰 uncurry
uncurryL :: (a -> b -> c) -> (a, b) -> c
uncurryL f ~(a, b) = f a b
Run Code Online (Sandbox Code Playgroud)
然后我们可以用Zup一种说明这里发生的事情的方式编写递归分支
instance Zup b => Zup (a, b) where
zup f = uncurryL (zup . f)
Run Code Online (Sandbox Code Playgroud)