Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

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:

  • a function translateToken :: String -> String
  • a function 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
like image 200
inktrap Avatar asked Dec 06 '22 15:12

inktrap


1 Answers

You can create a type containing the functions you want e.g.

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

then create values for Spanish and Russian.

like image 185
Lee Avatar answered Dec 09 '22 14:12

Lee