在以下代码中
module Main where
import Control.Monad.State
import Control.Applicative
type Code = String
toSth :: Read a => State [Code] a
toSth = state $ \(c:cs) -> ((read c), cs)
codes = ["12", "True", ""]
data Tick = Tick {n :: Int, bid :: Bool} deriving (Show)
res = runState (pure Tick <*> toSth <*> toSth) codes
main = print res
我得到了正确的结果
(Tick {n = 12, bid = True},[""])
但我的问题是重复
pure Tick <*> toSth <*> toSth
即,如果记录有100个字段,那么我必须写<*> toSth
100次,这看起来不像Haskell。
在foldl
有没有办法让<*>
?我知道标准的foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b
在这里不起作用,因为累加器类型在每次迭代中都会改变。
非常感谢!
这可以通过一些先进的generics库来完成,比如generics-sop。
泛型库将数据类型转换为某种“统一”表示形式。这些库还提供了创建或修改此类表示的功能。我们可以处理表示,然后转换回原始数据类型。
{-# language DeriveGeneric, TypeApplications #-}
import qualified GHC.Generics
import Generics.SOP (Generic,to,SOP(SOP),NS(Z),hsequence,hcpure)
import Data.Proxy
data Tick = Tick {n :: Int, bid :: Bool} deriving (Show,GHC.Generics.Generic)
instance Generic Tick -- this Generic is from generics-sop
res :: (Tick, [Code])
res =
let tickAction :: State [Code] Tick
tickAction = to . SOP . Z <$> hsequence (hcpure (Proxy @Read) toSth)
in runState tickAction codes
hcpure
用有效的函数(这里是n-ary product)创建了一个toSth
,它知道如何创建产品的每个成员。我们必须通过带有约束的Proxy
来说服编译器。结果是一个产品,其中每个组件都包裹在State
中。
hsequence
就像sequenceA
,但是每种成分都有不同类型的n-ary产品。结果是相似的:Applicative
被“向外拉”。
SOP
和Z
是包装产品的构造函数,让我们调用to
来获得原始Tick
类型的值。
可以给res
这个更通用的签名来处理作为Generics.SOP.Generic
实例的任何单构造函数记录:
{-# language DataKinds #-}
res :: (Generic r, Generics.SOP.Code r ~ '[ xs ], Generics.SOP.All Read xs) => (r,[Code])
res =
let tickAction = to . SOP . Z <$> hsequence (hcpure (Proxy @Read) toSth)
in runState tickAction codes