In object oriented programming languages you often have multiple constructors that set up objects of a class, for example a MyInteger
object could be constructed from an built-in int or a string:
class MyInteger {
int _value;
MyInteger (int value) {
_value = value;
}
MyInteger (String value) {
_value = String.parseInt(value);
}
}
What would be the idomatic way to do this in Haskell? As far as I understand in Haskell the sum type
data MyInteger = Integer Int | String String
is either an Integer
or String
and not a single type like in the oo-example above. And I can't define a logic for the value constructor String
that would take a String
and "return" a MyInteger
.
Do I have to define separate functions like this:
myIntegerFromString :: String -> MyInteger
myintegerFromString inputString = ...<parsing logic on inputString>....
and then call it whenever I want to create a MyInteger
from a string
main = do
...
let aMyInteger = myIntegerFromString "4"
...
Addendum:
The creation of an "object" from Int
and String
was merely meant as a minimal example. I am more interested in the general approach of having variables of a type X that can be created from various other types Y,Z,... and how this would be solved in Haskell. Precisely because I don't want to misuse Haskell while thinking in object-oriented ways, I am asking for an idiomatic pattern to model this in Haskell. This is why a solution that solves the parsing of Int
s from String
s is too specific.