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
).
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
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?
-- 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. "
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
A class
, sometimes referred to as a "type 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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.