Reputation: 245
I'm new to functional programming and Haskell, and having really difficult time understanding making of your own data types. As a learning source I have been using http://learnyouahaskell.com/, but I'm still unable to grasp some ideas.
My specific problem is, that I'm trying to create a show Instance for my custom data type, which always shows '+' symbol in front of whatever is showed (in my case input 555 would be "+555"). This is how I've been trying to solve it.
data CountryCode = CountryCode Integer deriving Eq
instance Show CountryCode where
show _ = "+" : _
And this is what I get when I try to load it.
[1 of 1] Compiling Main ( phonetest.hs, interpreted )
phonetest.hs:6:14: error:
• Couldn't match type ‘[Char]’ with ‘Char’
Expected type: String
Actual type: [[Char]]
• In the expression: "+" : _
In an equation for ‘show’: show _ = "+" : _
In the instance declaration for ‘Show CountryCode’
phonetest.hs:6:20: error:
• Found hole: _ :: [[Char]]
• In the second argument of ‘(:)’, namely ‘_’
In the expression: "+" : _
In an equation for ‘show’: show _ = "+" : _
• Relevant bindings include
show :: CountryCode -> String (bound at phonetest.hs:6:5)
Failed, modules loaded: none.
I can get something out of the error message, but not enough to make it work correctly. I also tried show (CountryCode _) = "+" : _
but haskell still complains. To me it seems pretty logical, but clearly there's some basic haskell knowledge I'm lacking.
Upvotes: 1
Views: 100
Reputation: 476503
You should unpack the data constructor, and thus obtain the parameter x
. We can then use guards to check if the value is positive or negative. In case it is positive, we can prepend 'x'
to the result of show x
:
instance Show CountryCode where
show (CountryCode x) | x >= 0 = '+' : show x
| otherwise = show x
or we can omit branching in a positive and negative case like @chepner suggests with:
instance Show CountryCode where
show (CountryCode x) = '+' : show x
Upvotes: 4