Reputation: 2039
if I have a custom data type that takes in a string representation of a Boolean
(ie "true"
or "false"
). How do I make by data type convert that to a Bool
with out having to perform an actions on the input before?
for example
λ: MyData "false"
MyData False
Upvotes: 0
Views: 1497
Reputation: 647
You simply can't.
First, String
type has values irrepresentable as Boolean
, like "foo"
. What do your datatype supposed to return on MyData "foo"
? an error
?
Second, there is the part of haskell philosophy: do everything explicitly. No typecasts, no Foo foo = 1
which calls foo(const int&)
like in C++. And that is a good part.
P.S.: if you get the values from input, just write yourself a proper parser (not just a Read
instance - it crushes thread on failure).
Upvotes: 0
Reputation: 531165
You can also use the OverloadedStrings
extension in GHC and declare your type to be an instance of IsString
:
newtype MyData = MyData Bool deriving (Show)
instance IsString MyData where
fromString "false" = MyData False
fromString "true" = MyData True
fromString "False" = MyData False
fromString "True" = MyData True
Now you can say something like:
> "false" :: MyData
MyData False
> "True" :: MyData
MyData True
Upvotes: 0
Reputation: 19203
You can't without a function, normally you just define a function that returns the new type, for instance:
newtype MyData = MyData Bool
myData :: String -> MyData
myData "false" = MyData False
myData "true" = MyData True
-- Need to decide how to handle invalid arguments
Now instead of writing MyData "false"
you write myData "false"
.
Upvotes: 6