【发布时间】:2013-04-28 18:54:41
【问题描述】:
我想知道以下两种策略中哪一种对于重载函数最有效(在我的示例中是函数 teX)。
-
使用
data和模式匹配:data TeX = TeXt String | TeXmath String deriving (Show,Read,Eq) teX (TeXt t) = t teX (TeXmath t) = "$$" ++ t ++ "$$" -
或者使用一点抽象:
class TeX t where teX :: t -> String newtype TeXt = TeXt String deriving (Show,Read,Eq) instance TeX TeXt where teX (TeXt t) = t newtype TeXmath = TeXmath String deriving (Show,Read,Eq) instance TeX TeXmath where teX (TeXmath t) = "$$" ++ t ++ "$$"
当然第一个更容易使用,第二个更容易丰富;但我想知道一个是否会比另一个运行得更快,或者 Haskell 是否会以完全相同的方式实现它们。
【问题讨论】:
-
第二个并不是类型类的真正含义,看起来您正在尝试在 OOP 中复制类
-
后一个模块有点复杂,因为它涵盖了这么多,但请注意,该方法具有您设想的类所没有的可扩展性:您将如何引入函数
html :: t -> String' andmarkdown :: t -> String` 和类似的函数,例如在该包的其他地方定义的?
标签: haskell