[英]What is the haskell equivalent of an interface?
I would like to implement modules that are guaranteed to export a similar set of functions. 我想实现保证导出类似功能集的模块。
For the sake of an example: Suppose I want to translate a word. 为了举个例子:假设我想翻译一个单词。 Every word is mapped from the source language (let's say
English
) to the target language (let's say Spanish
and Russian
). 每个单词都从源语言(比方说
English
)映射到目标语言(比方说Spanish
和Russian
)。
My main application would import the models for Spanish and Russian and chooses a default model, Russian. 我的主要应用程序将导入西班牙语和俄语的模型,并选择默认模型,俄语。 I would like to guarantee, that each model has:
我想保证,每个型号都有:
translateToken :: String -> String
translateToken :: String -> String
translatePhrase :: String -> String
translatePhrase :: String -> String
in which the specific behaviour is implemented. 其中实现了特定的行为。
How do I do this? 我该怎么做呢?
Edit , regarding Lee's answer: How do i create data types with record syntax that contain functions that use guards? 编辑 ,关于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
You can create a type containing the functions you want eg 您可以创建包含所需功能的类型,例如
data Model = Model { translateToken :: String -> String,
translatePhrase :: String -> String }
then create values for Spanish and Russian. 然后为西班牙语和俄语创造价值。
That would be typeclasses. 这将是类型。 From Learn You a Haskell : "Typeclasses are more like interfaces. "
从了解你是一个Haskell :“类型更像是接口。”
You'd define your own typeclass (untested): 你定义了自己的类型类(未经测试):
class Translation a where
translateToken :: a -> String -> String
translatePhrase :: a -> String -> String
and implement it as 并实现它
instance Translation Spanish where
translateToken = spanishTranslateToken
translatePhrase = spanishTranslatePhrase
See also Real Word Haskell on typeclasses 另请参阅类型上的真实单词Haskell
A class
, sometimes referred to as a "type class". 一个
class
,有时也称为“类型类”。 Don't get this confused with your usual OO-classes though, Haskell classes don't have data, and generally don't have implementations (with the exception of generic defaults). 不要把它与你常用的OO类混淆,但Haskell类没有数据,并且通常没有实现(通用默认值除外)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.