-2

I have been using Map.lookup in Haskell and I am constantly getting the following error:

Couldn't match expected type `[Char]` with actual type `Maybe String`.

Is there a quick and simple way to convert this?

dfeuer
  • 48,079
  • 5
  • 63
  • 167
sudobangbang
  • 1,406
  • 10
  • 32
  • 55

2 Answers2

1

Without seeing your code, there's no way to say for sure, but most likely you've looked something up in a Map and expected to get a String (which is the same as [Char]). In fact, lookup returns a Maybe String, so it can return Nothing if the requested key is not in the Map.

dfeuer
  • 48,079
  • 5
  • 63
  • 167
1

You can't "convert" x :: Maybe String to a String, unless you decide how to handle the case where x is Nothing -- in your case, when the element in the Map was not found.

Try something like this:

case Map.lookup ... of
   Nothing  -> ... -- handle the "not found" case
   Just str -> ... -- handle the "found" case, str contains the found string value

There's also a maybe function which can provide a shorter alternative in some cases, but I'd recommend learning how to use a case first.

Joe Hillenbrand
  • 845
  • 9
  • 26
chi
  • 111,837
  • 3
  • 133
  • 218
  • 2
    I'd like point out to beginners that this highlights one of the best things about Haskell. Haskell forces the programmer to think about the non-happy path up front and handle it explicitly. This is counter to most other programming languages, but it leads to much more reliable programs. – Joe Hillenbrand Mar 19 '16 at 00:27