• =?UTF-8?B?TWl4aW5nIG1vbmFkcyAvIGJpbmRpbmc=?=

    From =?UTF-8?B?VGhvYWkgTmd1eWVu?=@me@thoaionline.com to comp.lang.haskell on Tue Aug 6 14:54:01 2019
    From Newsgroup: comp.lang.haskell

    Hi fam,
    This is a fairly noob question. Considering the following imaginary functions: someCalculation :: String -> Maybe String
    someCalculation =3d Just
    main :: IO ()
    main =3d getLine >>=3d someCalculation >>=3d 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...
    Many thanks,
    --- Synchronet 3.21d-Linux NewsLink 1.2
  • From Barry Fishman@barry@ecubist.org to comp.lang.haskell on Wed Aug 7 09:30:06 2019
    From Newsgroup: comp.lang.haskell


    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

    --- Synchronet 3.21d-Linux NewsLink 1.2
  • From =?UTF-8?B?VGhvYWkgTmd1eWVu?=@me@thoaionline.com to comp.lang.haskell on Wed Aug 7 14:41:05 2019
    From Newsgroup: comp.lang.haskell

    Thanks for your help guys. I'm gonna go with Barry's implementation (convert and wrap Maybe into IO)
    --- Synchronet 3.21d-Linux NewsLink 1.2