电梯施工人员
使用类型类,我们可以定义liftA
/的通用版本ap
。棘手的部分是推断何时停止提升并返回结果。在这里,我们使用构造函数是具有与字段一样多的参数的柯里化函数,并且结果类型不是函数的事实。
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
import Text.Read
-- apF
-- :: Applicative f
-- => (i -> f a)
-- -> (a -> a -> ... -> x) -- constructor type
-- -> (i -> i -> ... -> f x) -- lifted function
class Applicative f => ApF f i a s t where
apF :: (i -> f a) -> f s -> t
-- Recursive case
-- s ~ (a -> ...)
-- t ~ (i -> ...)
instance (a ~ a', t ~ (i -> t'), ApF f i a s' t') => ApF f i a (a' -> s') t where
apF parseArg fconstr i = apF parseArg (fconstr <*> parseArg i)
-- Base case
-- s ~ x -- x assumed not to be a function type (not (y -> z) for any y and z)
-- t ~ f x
instance {-# OVERLAPPABLE #-} (t ~ f x, Applicative f) => ApF f i a x t where
apF _ fconstr = fconstr
liftF :: ApF f i a s t => (i -> f a) -> s -> t
liftF parseArg constr = apF parseArg (pure constr)
main = do
let lookup :: Int -> Maybe Integer
lookup i =
case drop i [2,3,5,7,11,13] of
[] -> Nothing
a : _ -> Just a
print $ liftF lookup (,,) 0 2 5
更高种类的记录和泛型
另一种解决方案是首先通过包装每个字段的类型函数来参数化记录,以便我们可以放置各种其他相关类型的东西。这些允许我们通过使用 Haskell 泛型遍历那些派生结构来生成和使用实际记录。
data UserF f = User
{ name :: f @@ String
, age :: f @@ Int
} deriving G.Generic
type User = UserF Id
类型函数是使用类型族定义的(@@)
(HKD
在上面链接的博客文章中)。与此答案相关的是恒等函数。
type family s @@ x
type instance Id @@ x = x
type instance Cn a @@ x = a
data Id
data Cn (a :: *)
例如,我们可以在 a 中收集用于解析 CSV 的索引UserF (Cn Int)
:
userIxes = User { name = 0, age = 2 } :: UserF (Cn Int)
给定这样的参数化记录类型 ( p = UserF
) 和索引记录 ( ixes :: p (Cn Int)
),我们可以解析 CSV 记录 ( r :: [String]
),parseRec
如下所示。这里使用generics-sop。
parseRec :: _
=> p (Cn Int) -> [String] -> Maybe (p Id)
parseRec ixes r =
fmap to .
hsequence .
htrans (Proxy :: Proxy ParseFrom) (\(I i) -> read (r !! i)) .
from $
ixes
让我们自下而上分解代码。generics-sop提供组合器以统一的方式转换记录,就像使用列表一样。最好遵循适当的教程来了解底层细节,但为了演示,我们将假设from
和之间的管道中间to
实际上是在转换列表,使用动态类型Field
来键入异构列表。
from
将记录转换为其异构字段列表,但由于它们都是Int
列表,因此现在确实是同质的from :: p (Cn Int) -> [Int]
。
这里使用(!!)
and read
,我们使用给定的 index 获取并解析每个字段i
。htrans Proxy
基本上是map
:(Int -> Maybe Field) -> [Int] -> [Maybe Field]
。
hsequence
基本上是sequence :: [Maybe Field] -> Maybe [Field]
。
to
将字段列表转换为具有兼容字段类型的记录,[Field] -> p Id
.
最后一步很轻松:
parseUser :: Record -> Maybe User
parseUser = parseRec $ User { name = 0, age = 2 }