Home > database >  IO() Recursive Type Matching Issue
IO() Recursive Type Matching Issue

Time:12-16

So I got this problem as an exam and I don't really get how to match the data types.

I need to get the console to ask you about a number (must be above 0), and until you say 0 it keeps asking, when you say 0 it must stop and tell you the lowest number you said, example:

Give me a number (0 to finish): 4
Give me a number (0 to finish): 8
Give me a number (0 to finish): 9
Give me a number (0 to finish): 2
Give me a number (0 to finish): 0
The minimum value you said is: 2

I know it might be simple but I really don't get it to be done in a single function with type :: IO()

This is the code I made so far:

minPos:: IO ()
minPos = do
         putStrLn ("Give me a number (0 to finish): ")
         a <- getLine
         minPos' (read a)

minPos' :: [Char] -> IO ()
minPos' a = if (read a) == 0 && (read a) > 0 then
                                                    --This should print the lowest number given
                do putStrLn "The minimum value you said is: " 
            else
                do
                putStrLn ("Give me a number (0 to finish): ")
                b <- getLine
                minPos' (minPos'' a (read b))

minPos'':: [Char] -> [Char] -> [Char]
minPos'' a b =  if (b < a && (read b) > 0) then
                    minPos' (read b)
                else minPos' (read a)

CodePudding user response:

You already apply read a in the minPos, hence minPos' should take an Int and thus have signature Int -> IO (). For the same reason minPos'' makes not much sense.

You can define a function with:

readValue :: IO Int
readValue = do
    putStrLn ("Give me a number (0 to finish): ")
    readLn

minPos:: IO ()
minPos = do
    a <- readValue
    case a of
        0 -> putStrLn "No values entered"
        n -> minPos' a

minPos' :: Int -> IO ()
minPos' mn = do
    a <- readValue
    case a of
        …

Here the mn parameter of minPos' is the thus far obtained minimum value. In case a is thus 0, you need to print that number. In case it reads another item, it should take the minimum of the two, for example with min :: Ord a => a -> a -> a and make a recursive call with that minimum. I leave filling in the part as an exercise.

  • Related