首页 文章

非详尽模式错误

提问于
浏览
0

我的函数将Maybe Int列表作为其参数 . 如果元素= Nothing它应该打印一个 . 如果元素是Just Int,它将打印数字 . 我以为我已经捕获了一个基础但我认为我没有得到正确的一个..我得到一个非详尽的模式错误 .

replaceValue :: [Maybe Int] -> String
replaceValue (x:xs) 
    | (x:xs) == []        = []
    | isNothing x == True = '.':replaceValue xs
    | isJust x == True    = intToDigit(fromJust x):(replaceValue xs)

向正确的方向点头将受到高度赞赏! :-)

2 回答

  • 4

    模式 x:xs 仅匹配非空列表 . 守卫 (x:xs) == [] 永远不会成功 .

    你可能意味着这个:

    replaceValue [] = []
    replaceValue (x:xs)
      | isNothing x = ...
      | isJust    x = ...
    

    另请注意, ... == True... 的结果相同 . ;-)

  • 6

    @MathematicalOrchid已经回答了 .

    我想补充一点,使用 isNothing/isJust/fromJust 使您的代码比应有的更复杂 . 此外, fromJust 一般是危险的,因为如果你将 Nothing 传递给它会崩溃 - 在这里你用 isJust 守卫正确地防止这种情况,但在大型程序中很容易忘记这一点 .

    好消息是你可以使用模式匹配来避免所有这些辅助功能:

    replaceValue :: [Maybe Int] -> String
    replaceValue []             = []
    replaceValue (Nothing : xs) = '.' : replaceValue xs
    replaceValue (Just a : xs)  = intToDigit a : replaceValue xs
    

    一旦你对Haskell更加熟悉,你将能够以更紧凑的形式重写标准的递归方案,例如上面的那个,利用一些更高阶的库函数 .

    replaceValue :: [Maybe Int] -> String
    replaceValue = map (maybe '.' intToDigit)
    

相关问题