首页 > 解决方案 > 使用警卫检查字符串的每个字符 [Haskell]

问题描述

我在尝试使用 Haskell 时遇到问题。当我看到字符时,我想读取一串数字并打印各种消息。

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"

问题是这样的。我想打印“True\nFalse\nMaybe\n”但我只打印“True\n”。我知道我的问题是,当警卫采取行动时,它会离开功能。但我不知道如何在不离开 ' 的情况下检查整个字符串test_parse

如果有人有想法,谢谢。

标签: parsinghaskellrecursionguard

解决方案


无论前缀上的结果如何,您都想检查每个后缀。一个例子:

-- 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

推荐阅读