【问题标题】:If error, assign a specific value to variable如果出错,给变量赋值
【发布时间】:2022-10-13 23:00:16
【问题描述】:

所以我有这个代码片段:where exponent = read (tail (dropWhile (/= '^') (head xs))) :: Inttail 中的列表可能为空,这意味着在空列表中查找尾部时会出错。有没有办法做类似的事情:if error: exponent = 1

如果它有任何帮助,这是完整的功能:)

internalRepresentation :: [String] -> [(Int,Char ,Int)]
internalRepresentation xs
    |null xs = []
    |all isDigit (head xs) = (read (head xs), ' ', 0) : internalRepresentation (tail xs)
    |head (head xs) == '-' = (-read (takeWhile isDigit (pos_mon)) :: Int, head (dropWhile isDigit (pos_mon)), exponent) : internalRepresentation (drop 1 xs)
    |otherwise = (read (takeWhile isDigit (head xs)) :: Int, head (dropWhile isDigit (head xs)), exponent) : internalRepresentation (drop 1 xs)
    where pos_mon = tail (head xs)
          exponent = read (tail (dropWhile (/= '^') (head xs))) :: Int

谢谢你的时间!

【问题讨论】:

    标签: haskell


    【解决方案1】:

    您可以将您的列表包装成 maybe - monad (wiki maybe/monad)。

    【讨论】:

      【解决方案2】:

      函数 readheadtail 是部分函数,​​可能会失败并出现错误,正如您所经历的那样。这就是为什么许多人避免使用这些功能的原因。就个人而言,我会这样写:

      import Text.Read (readMaybe)
      
      internalRepresentation' :: String -> (Int, Char, Int)
      internalRepresentation' xs =
        case reads xs of
          [(n, x:xs')] ->
            case readMaybe (drop 1 (dropWhile (/= '^') (x:xs'))) of
              Just e -> (n, x, e)
              Nothing -> error "Malformed exponent"
          _ -> error "Some error message"
      
      internalRepresentation :: [String] -> [(Int,Char ,Int)]
      internalRepresentation xs = map internalRepresentation' xs
      

      如果您对输入进行更多限制,您也可以避免丑陋的drop 1 (dropWhile (/= '^') (x:xs'))。当然,第二条错误消息可以改进。但我不完全确定这个函数实际上应该做什么,所以我无能为力。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-23
        • 2021-12-04
        • 1970-01-01
        • 2016-04-24
        • 2014-04-30
        • 1970-01-01
        • 2020-07-31
        • 2020-06-29
        相关资源
        最近更新 更多