Haskell中的"条件错误"

pie*_*ier 0 haskell

我的原始代码如下所示,工作正常.我想添加'ind'的范围检查,在修改后的版本中我添加了一个if语句.当我运行它时,我得到一个"有条件的类型错误",我认为它是因为输出定义[[String]]而不是IO()?

有没有其他方法来检查保持的值的范围ind并产生像"错误"/"outofrange"的输出?

原始代码

retrieve :: [Int] -> [[String]] -> [[String]]
retrieve [] dat = [[]]
retrieve ind dat = [exC ind d | d <- dat]
Run Code Online (Sandbox Code Playgroud)

修改后的代码

retrieve :: [Int] -> [[String]] -> [[String]]
retrieve [] dat = [[]]
retrieve ind dat = if ind>3
                       then putStrLn "not found"
                       else [exC ind d | d <- dat]
Run Code Online (Sandbox Code Playgroud)

谢谢,

Ste*_*202 6

该代码实际上有两个错误.

  • 你需要使用error,因为它有类型String -> a而不是String -> IO ()
  • 您可以应用>[Int]Int.假设你想测试ind长度是否最多3,你将不得不打电话length.

例:

retrieve :: [Int] -> [[String]] -> [[String]]
retrieve [] dat = [[]]
retrieve ind dat | length ind > 3 = error "not found"
                 | otherwise      = [exC ind d | d <- dat]
Run Code Online (Sandbox Code Playgroud)


GS *_*ica 5

替换putStrLnerror.这将导致您的程序完全中止(除非某些更高级别捕获异常.)

您编写的内容的问题是您已声明了纯类型,然后尝试执行IO,这是不允许的.