parsing - 使用警卫检查字符串的每个字符 [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
。
如果有人有想法,谢谢。
解决方案
无论前缀上的结果如何,您都想检查每个后缀。一个例子:
-- 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
推荐阅读
- react-native - 如何从 WebView 向 React Native 发送消息?
- csv - 如何使用 CsvHelper 从 .csv 文件中的多个对象中检索数据?
- python-3.x - folium.GeoJson(some_data) - 如何设置标记类型?
- mysql - 检查点是否在多边形中给出空值
- c++ - 在 Boost.uBLAS 中直接使用 vector_expression
- php - SQLSTATE[HY000] [2002] 在 Docker 中运行多个 laravel 项目时连接被拒绝
- angular - 动态改变间隔 Angular 的频率
- postgresql - JSONB 像数组一样表示jsonb键值
- hash - Sybase 哈希行
- python - 如何在 MongoDB 中的数组内编辑字典内的值?