Search code examples
parsinghaskellrecursionguard

Check every character of a string with guards [Haskell]


i have a problem when i'm trying to use Haskell. I want to read a string of number and print various messages when i see characters.

import System.Environment
import System.Exit
import Data.List
import Control.Monad


test_parse:: [Char] -> IO ()
test_parse [] = putStrLn "\n"
test_parse (a:b:c:xs)
            | a == '1' && b == '2' && c == '3' = putStrLn ("True")
            | a == '2' && b == '3' && c == '4' = putStrLn ("False")
            | a == '4' && b == '5' && c == '6' = putStrLn ("maybe")
            | otherwise = test_parse (b:c:xs)

main = do
    let numbers = "123456"
    let loop = do
            goGlenn <- getLine
            test_parse numbers
            putStrLn goGlenn
            when (goGlenn /= "start") loop
    loop
    putStrLn "ok"

The problem is this. I would like to print "True\nFalse\nMaybe\n" But I print just "True\n". I know my problem is that when an action is made by the guards, it leaves the function. But I don’t see how to check the entire string without leaving 'test_parse.

If anyone have a idea, thanks.


Solution

  • You want to check every suffix, regardless of the result on the prefix. One example:

    -- output a string based on the first 3 characters of the input
    classify :: String -> IO ()
    classify xs = case take 3 xs of
                    "123" -> putStrLn "True"
                    "234" -> putStrLn "False"
                    "456" -> putStrLn "maybe"
                    otherwise -> return ()
    
    -- call classify repeatedly on different suffixes of the input
    test_parse :: String -> IO ()
    test_parse [] = return ()
    test_parse all@(_:xs) = do
        classify all
        test_parse xs