Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.haskell > #541

Re: Mixing monads / binding

From Barry Fishman <barry@ecubist.org>
Newsgroups comp.lang.haskell
Subject Re: Mixing monads / binding
References <dwg2F.243764$Kf5.47661@fx42.iad>
Message-ID <7nk1bp6r35.fsf@ecube.ecubist.org> (permalink)
Organization Easynews - www.easynews.com
Date 2019-08-07 09:30 -0400

Show all headers | View raw


On 2019-08-06 14:54:01 +00, Thoai Nguyen wrote:
> This is a fairly noob question. Considering the following imaginary functions:
>
> someCalculation :: String -> Maybe String
> someCalculation = Just
>
> main :: IO ()
> main = getLine >>= someCalculation >>= putStrLn
>
>
> What I want to do is to run a non-deterministic calculation on an
> input string, then print the output. In this case, 2 different monads
> are in use (Maybe & IO). Of course this wouldn't work due to incorrect
> typing.
>
> What would be the right way to handle something like this in Haskell?
>
> The someCalculation implementation is just a placeholder, but you get the idea...

The first >>= needs to have the same type of Monad on each side of it,
which you are not doing.  Also if you want to output the result though
putStrLn you need a function that converts you Maybe back to a String.

answerString :: Maybe String -> String
answerString = show

If you want to keep someCalculation free of the IO Monad you can nest
the Maybe inside the IO Monad:

 getLine >>= return . someCalculation >>= putStrLn . answerString

or:

 getLine >>= return . answerString . someCalculation >>= putStrLn

Note that any 'someCalculation >>= whatever' must return a Maybe, so you
can't go from 'Maybe a' to 'IO a' using just >>= operations.
--
Barry Fishman

Back to comp.lang.haskell | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Mixing monads / binding Thoai Nguyen <me@thoaionline.com> - 2019-08-06 14:54 +0000
  Re: Mixing monads / binding Benjamin Esham <usenet@esham.io> - 2019-08-06 19:37 +0000
  Re: Mixing monads / binding Barry Fishman <barry@ecubist.org> - 2019-08-07 09:30 -0400
    RE: Re: Mixing monads / binding Thoai Nguyen <me@thoaionline.com> - 2019-08-07 14:41 +0000

csiph-web