目前使用GHC,Data.Data/Data.Typeable和GHC.Generics进行泛型编程的选项有2个(如果你计算的是3个),那么这两个选项都可以从基础包中获得.那么,每个的优点和缺点是什么?GHC.Generics是"现代"方式而Data.Data是过时的,只是为了向后兼容而保留?
我基本上试图看看我是否可以在Haskell中模拟一个ORM框架,这样如果用户想要创建一个数据库模型,他们会做这样的事情
data Car = Car {
company :: String,
model :: String,
year :: Int
} deriving (Model)
Run Code Online (Sandbox Code Playgroud)
表格为"Car",列为公司,型号,年份
要在Haskell中执行此操作,您必须使用类和泛型的组合,这就是我遇到困难的地方.使用本教程(http://www.haskell.org/ghc/docs/7.4.1/html/users_guide/generic-programming.html),我想出了这个(基本上是复制和重命名,所以我可以得到代码工作)
{-# LANGUAGE DeriveGeneric, TypeOperators, TypeSynonymInstances, FlexibleInstances #-}
module Main where
import GHC.Generics
class SModel b where
s_new :: b -> IO()
instance SModel Int where
s_new s = putStrLn s++":Int"
instance SModel Integer where
s_new s = putStrLn s++":Integer"
instance SModel String where
s_new s = putStrLn s++":String"
class Model m where
new :: m a -> IO() …Run Code Online (Sandbox Code Playgroud)