Home > Software engineering >  How to re-use a function to effectively 'loop' in Haskell
How to re-use a function to effectively 'loop' in Haskell

Time:11-10

I've got a short interaction dialog where the computer asks for a number, and if it's smaller than 77, it states it's too small and to try again.

The issue I have on hand is probably something simple, but as I'm relatively new I can't seem to get it too work, nor can find any related issues online.


import Text.Read

myread :: IO Int
myread  = do putStr "Please enter a number: "             
             x <- readLn             
             return x

isItLarge :: IO()
isItLarge = do
              result <- myread;
              if result < 77 then putStrLn "Tiny, try again!";
                                  myread
                             else putStrLn "Massive!";
               
               

In my logic, calling myread should revert it back to the top and allow you to continue until n > 77 is reached. Any help would be appreciated:)

Cheers for the help guys, I've got it now. From initially struggling by not taking out then putStrLn "Tiny, try again!" and replacing the block with what's below I understand now

if result < 77 then do putStrLn "Tiny, try again!";
                                   isItLarge
                           else putStrLn "Massive!";

CodePudding user response:

For the particular program in your question, the simplest approach is to just replace your second call to myread with a recursive call to isItLarge.

  • Related