什么是接口的haskell等价物?

ink*_*rap 4 haskell design-patterns interface

我想实现保证导出类似功能集的模块.

为了举个例子:假设我想翻译一个单词.每一个字从源语言映射(比方说English)目标语言(比方说,SpanishRussian).

我的主要应用程序将导入西班牙语和俄语的模型,并选择默认模型,俄语.我想保证,每个型号都有:

  • 一个功能 translateToken :: String -> String
  • 一个功能 translatePhrase :: String -> String

其中实现了特定的行为.

我该怎么做呢?

编辑,关于Lee的答案: 如何使用包含使用防护的功能的记录语法创建数据类型?

-- let's suppose I want to use a function with guards in a record.
-- how can and should i define that?

data Model  = Model { translateToken :: String -> String}

-- idea 1) should I define the functions separately, like this?
-- how do I do this in a way that does not clutter the module?
f l
  | l == "foo" = "bar"

main :: IO ()
main = print $ translateToken x "foo"
  where
    x = Model {translateToken=f}
    -- idea 2) define the function when creating the record,
    -- despite the syntax error, this seems messy:
    -- x = Model {name=(f l | l == "foo" = "bar")}

-- idea 3) update the record later
Run Code Online (Sandbox Code Playgroud)

Lee*_*Lee 15

您可以创建包含所需功能的类型,例如

data Model = Model { translateToken :: String -> String,
                     translatePhrase :: String -> String }
Run Code Online (Sandbox Code Playgroud)

然后为西班牙语和俄语创造价值.

  • @MichalCharemza因为当你使用一个类型类`C`作为Java接口时,你很快就会因为`C`不是一个类型而被绊倒,并开始在`C`周围定义一个存在类型,如`data T = forall t.C t => T t`.这是一个众所周知的Haskell [反模式](https://lukepalmer.wordpress.com/2010/01/24/haskell-antipattern-existential-typeclass/).注意:我大多同意Luke Palmer的说法,这通常是矫枉过正的,并且在使用带功能的基本记录时并没有获得任何好处.然而,在某些特定情况下,我认为"反模式"是合理的. (7认同)
  • @MichalCharemza - 我认为这种方法比较简单,因为你不需要为每个翻译实例创建一个新类型(即`SpanishTranslation`,`RussianTranslation`).另一个优点是你可以将记录放入集合中并将它们一起操作,这对于类型类来说很尴尬.我还认为这更接近于OO语言中接口的使用,其中行为耦合到接收器而不是类型. (2认同)