mb1*_*b14 7 haskell haskell-platform
haskell中的记录或简单ADT几乎等同于盒装元组.有没有办法(理想情况下是一些花哨的扩展或来自haksell平台的lib)允许在这种类型和元组之间进行转换?
我(相当)是haskell的新手,我正在尝试在Haskell中构建一些报告工具.这涉及读/写csv文件和数据库表.使用元组的事情非常简单,但在使用普通类时需要一些锅炉板.样板接缝几乎完全相同,但我没有找到一个很好的方法只做一次,除了可能做转换(数据< - >元组)并使用从元组到CSV /表的本机转换.
到目前为止我得到的所有答案都假定我需要一些完全通用的东西,我想要元组.我不想要元组,我有元组,我不想要它们,因此需要转换它们.实际上我只想减少锅炉板(到0 :-)),但我不需要为每种类型都使用相同的功能.
例如,我可以通过展开其构造函数轻松地将元组转换为任何元素.问题是我需要uncurryN,我在任何地方都找不到(除了模板haskell教程).反过来更难做到.
我不是要求一个解决方案(尽管我得到的所有答案都很棒,因为我不熟悉Haskell中不同的元编程方式)但更多,因为我不喜欢重新发明轮子,如果轮子已经存在(例如,这个不连续的,可以用手写到20并包装在漂亮的包装中)
显然存在一个不成熟的包,但它仍然解决了一半的问题.
你可能想看看GHC.Generics.它基本上将每个ADT编码为products((,))和sums(Either).例如,以下是使用泛型显示此表示的方法:
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
import GHC.Generics
class Tuple p where
showRepresentation :: p -> String
default showRepresentation :: (Generic p, GTuple (Rep p)) => p -> String
showRepresentation = gshowRepresentation . from
class GTuple p where
gshowRepresentation :: p x -> String
instance Tuple k => GTuple (K1 i k) where
gshowRepresentation (K1 t) = showRepresentation t
instance GTuple f => GTuple (M1 i c f) where
gshowRepresentation (M1 f) = gshowRepresentation f
instance (GTuple f, GTuple g) => GTuple (f :*: g) where
gshowRepresentation (f :*: g) = gshowRepresentation f ++ " * " ++ gshowRepresentation g
-- Some instances for the "primitive" types
instance Tuple Int where showRepresentation = show
instance Tuple Bool where showRepresentation = show
instance Tuple () where showRepresentation = show
--------------------------------------------------------------------------------
data Example = Example Int () Bool deriving Generic
instance Tuple Example
main :: IO ()
main = putStrLn $ showRepresentation $ Example 3 () False
-- prints: 3 * () * False
Run Code Online (Sandbox Code Playgroud)
您可以在GHC.Generics模块中找到更多文档.我还找到了关于它的论文,Haskell的通用派生机制非常易读(这是我读过的少数几篇论文之一).