【问题标题】:Validate a list of positive integer numbers in Haskell验证 Haskell 中的正整数列表
【发布时间】:2023-01-10 00:48:36
【问题描述】:

我想写一个 Haskell 程序,从 stdin 读取整数正数列表,如果用户写不同的东西,比如负数列表、字符列表或不是列表的东西,程序需要建议用户并再次从 stdin 读取,直到用户写入正确的列表。 这是我写的,但如果用户键入一个包含字符或单个数字/字符的列表,但没有将其放在方括号中,程序就会结束。 相反,如果用户键入包含负数或空列表的列表,程序运行良好。 感谢您的建议。

main :: IO()
main = do  
  putStrLn "\nType a list of positive integers enclosed in square brackets and separated by commas:"
  list <- readIntList
  putStrLn "\nList:"
  print list

readIntList :: IO [Double]
readIntList = do
  readedList <- getLine
  let list = read readedList
  case checkList list && not (null list) of
    True -> return list
    False -> putStrLn "\nInvalid input, type again:" >> readIntList

checkList :: [Double] -> Bool
checkList = all checkNumber

checkNumber :: (Ord a, Num a) => a -> Bool
checkNumber n
  | n > 0 = True
  | otherwise = False

【问题讨论】:

  • 我是否理解正确,你的问题是如何改变你的程序,以便用户也可以输入一个没有方括号的值?
  • 是的,但在这种情况下(单个值是不正确的输入)程序应该警告用户并再次要求键入列表,而不是终止。

标签: list haskell


【解决方案1】:

尝试这个:

import Control.Monad
    import Text.Read
    
    main :: IO ()
    main = do
        putStrLn "Enter a list of positive integers:"
        input <- getLine
        case readMaybe input of
            Just xs -> if all (> 0) xs
                then do
                    -- the input is a valid list of positive integers
                    putStrLn "Valid input"
                else do
                    putStrLn "Invalid input, type again:"
                    main
            Nothing -> do
                putStrLn "Invalid input: not a valid list of integers"
                main

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多