I am testing examples in the Haskell Tutorial for C Programmers (Part 2) and am having a bit of trouble with this one....
showPet :: Maybe (String, Int, String) -> String
showPet Nothing = "none"
showPet (Just (name, age, species)) = "a " ++ species ++ " named " ++ name ++ ", aged " ++ (show age)
While it compiles, invoking it with
showPet ("cat",5,"felix")
results in
<interactive>:131:9:
Couldn't match expected type `Maybe (String, Int, String)'
with actual type `([Char], t0, [Char])'
In the first argument of `showPet', namely `("cat", 5, "felix")'
In the expression: showPet ("cat", 5, "felix")
In an equation for `it': it = showPet ("cat", 5, "felix")
Am I calling it incorrectly or is it a change in Haskell that renders this in need of a change (I have found a few)?
You specified in the type of showPet, that your first parameter should be of type showPet :: Maybe (String, Int, String), but you only supplied a (String, Int, String)
You'll need to "wrap" your value in some Maybe value to make this work. For maybes this is easy because if you have a value, you'll always just use Just (Just's type is a -> Maybe a)
The final working result is, showPet (Just ("cat",5,"felix"))
The type error is telling you that showPet expects Maybe something, but you are passing it something.
In Haskell the Maybe type is an explicit wrapper that indicates in the type system that a value might not be present. At runtime absence is signified by the Nothing value, and the presence of the value requires the Just wrapper.
So you need to call showPet with showPet (Just ("cat",5,"felix")).
Note that the way you call showPet closely matches its definition - the syntax for the call matches up with the syntax for the showPet (Just ... line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With