1

我想我错过了有一个元素列表但我找不到写它的方法有人可以帮助我的情况吗?

getBoard :: [String] -> [String]
getBoard (h:t) | isLOL h = h: getBoard (t)
               | otherwise = []


isLOL :: String -> Bool
isLOL [ ] = True
isLOL (h:t) | h>='a' && h<='z' || h >='A' && h<='Z' = isLOL t
            | otherwise = False
4

2 回答 2

1

首先,在您的定义中,问题是在模式(在您的情况下)匹配之后检查getBoard守卫(在 之后的东西)。因此,如果 to 的参数不匹配(即 is ),则不会检查两个分支(包括分支)。解决方案是在 上添加匹配:|h:tgetBoardh:t[]otherwise[]

getBoard (h:t) | isLOL h = h : getBoard t
               | otherwise = []
getBoard [] = []

但是,与失败的守卫匹配失败,所以你可以写成

getBoard (h:t) | isLOL h = h : getBoard t
getBoard _               = []

现在,至于如何使用 Prelude 中的递归方案以更好的方式编写此函数:

isLOL可以改写为

isLOL = all $ \h -> 'a' <= h && h <= 'z' || 'A' <= h && h<= 'Z'

并且getBoard可以类似地重写,注意如果每个字符它总是返回原始列表isLOL,否则返回空列表:

getBoard cs | all isLOL cs = cs
            | otherwise = []
于 2014-11-18T16:22:57.373 回答
1
getBoard [] = []

是你想要的线。像这样:

getBoard :: [String] -> [String]
getBoard [] = []
getBoard (h:t) | isLOL h = h: getBoard (t)
               | otherwise = []


isLOL :: String -> Bool
isLOL [] = True
isLOL (h:t) | h>='a' && h<='z' || h >='A' && h<='Z' = isLOL t
            | otherwise = False
于 2014-11-18T16:20:49.170 回答