[Haskell-cafe] Simple "Maybe" question
Matthew Walton
matthew at alledora.co.uk
Tue Jan 27 13:04:01 EST 2004
Jim Lewis wrote:
> I'm new to Haskell and can't find an example to solve a trivial problem.
>
> I have code like this:
> findBlank :: [] -> Int
> findBlank str = findIndex (==' ') str
>
> But interpreter complains elsewhere of mismatch of Int with Maybe Int. I want to handle the maybe only here and nowhere else.
>
> This just makes matters worse:
> findBlank str = Just findIndex (==' ') str
>
> Thanks.
The result type of findIndex (==' ') str is Maybe Int, therefore you
need to be prepared to handle both sides of a Maybe result, which could
be Just n (where n is some Int), or Nothing. The simplest solution is to
use 'case' to handle when findIndex returns Just n, and when findIndex
returns Nothing, although you'll need to find a suitable Int for
findBlank to return when findIndex returns Nothing.
Although were I writing the code, I'd be tempted to make findBlank
return a Maybe Int as well, and let the code which calls that deal with
Nothing as an error condition.
More information about the Haskell-Cafe
mailing list