[Haskell-beginners] maybe in IO

Gesh hseG gesh at gesh.uni.cx
Thu Aug 1 17:39:22 CEST 2013


On Thu, Aug 1, 2013 at 6:00 PM, vold <voldermort at hotmail.com> wrote:
> I've defined a function similar to
>
> check x assoc = let found = lookup x assoc in
>                     when (isJust found) $ putStrLn $ "found " ++ fromJust found
>
> which I've used several times from within the IO monad. Is there a more
> compact way of doing this?
Firstly, note that it is more idiomatic to move the IO code to other functions,
which would allow check to be pure.
Secondly, one can use the fact that Maybe is a Functor to rewrite check
as follows:
check x db = maybeToIO $ (putStrLn . ("found"++)) <$> x `lookup` db
  where maybeToIO = fromMaybe (return ())
The refactoring of maybeToIO isn't strictly necessary, but I found it clearer.
HTH,
Gesh




More information about the Beginners mailing list