Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Couldn't match expected type `Maybe (String, Int, String)' with actual type `([Char], t0, [Char])'

Tags:

haskell

ghci

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

like image 945
Dave Appleton Avatar asked Jul 13 '14 00:07

Dave Appleton


2 Answers

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

like image 129
Adam Wagner Avatar answered Oct 22 '22 16:10

Adam Wagner


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.

like image 41
GS - Apologise to Monica Avatar answered Oct 22 '22 17:10

GS - Apologise to Monica