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)

向正确方向点头将不胜感激!:-)

4

2 回答 2

6

@MathematicalOrchid 已经回答了。

我想补充一点, usingisNothing/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)
于 2014-10-01T17:01:54.203 回答
4

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

你可能是这个意思:

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

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

于 2014-10-01T16:49:41.820 回答