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


Groups > comp.lang.haskell > #514

Re: Get mapM to be lazy for IO

From Barry Fishman <barry@ecubist.org>
Newsgroups comp.lang.haskell
Subject Re: Get mapM to be lazy for IO
References <24548724-4bdd-402d-8a76-1403b7e87169@googlegroups.com>
Message-ID <7nmup95via.fsf@ecube.ecubist.org> (permalink)
Organization Easynews - www.easynews.com
Date 2018-12-13 09:52 -0500

Show all headers | View raw


On 2018-12-11 05:19:18 -08, kfjwheeler@gmail.com wrote:
> I'm kind of a beginner when it comes to Haskell.  Specifically with regards to IO.
>
> I'm tying to write a very simple program that asks the user to input a list of words.  It gets words until the user enters "done".
>
> I'm getting close, but it's still asking for input after I enter "done".  I can't seem to get mapM to be lazy in the way I want.

IO can be lazy, but the order of actions needs to preserved, so that
each putStrLn prompt precedes it's getLine.

The following is how I might write it.  I used the 'hFlush' call so I
could put out the prompt without forcing a newline, and then read the
word on the same line.  You can leave it out.

--8<---------------cut here---------------start------------->8---
#! /usr/bin/env runghc

import System.IO (hFlush, stdout)

main :: IO ()
main = do
  putStrLn "Hello.  Please enter words until 'done'."
  xs <- getWordList 1
  mapM_ putStrLn xs
  where getWordList :: Int -> IO [String]
        getWordList n = do
        putStr $ "Input number " ++ show n ++ ": "
        hFlush stdout
        x <- getLine
        if x == "done"
          then return []
          else do
            xs <- getWordList (n + 1)
            return (x : xs)
--8<---------------cut here---------------end--------------->8---

I would probably shorted the last 'else' to:
          else (x:) `fmap` getWordList (n + 1)

-- 
Barry Fishman

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


Thread

Get mapM to be lazy for IO kfjwheeler@gmail.com - 2018-12-11 05:19 -0800
  Re: Get mapM to be lazy for IO Mark Carroll <mtbc@bcs.org> - 2018-12-11 13:36 +0000
    Re: Get mapM to be lazy for IO Kaylen Wheeler <kfjwheeler@gmail.com> - 2018-12-12 17:52 -0800
      Re: Get mapM to be lazy for IO Paul Rubin <no.email@nospam.invalid> - 2018-12-12 19:29 -0800
    Re: Get mapM to be lazy for IO Kaylen Wheeler <kfjwheeler@gmail.com> - 2018-12-12 18:21 -0800
      Re: Get mapM to be lazy for IO Paul Rubin <no.email@nospam.invalid> - 2018-12-12 19:31 -0800
  Re: Get mapM to be lazy for IO Barry Fishman <barry@ecubist.org> - 2018-12-13 09:52 -0500
    Re: Get mapM to be lazy for IO Barry Fishman <barry@ecubist.org> - 2018-12-13 10:21 -0500
      Re: Get mapM to be lazy for IO Barry Fishman <barry@ecubist.org> - 2018-12-13 10:46 -0500

csiph-web