如何解决输入'otherwise'上的Haskell解析错误



我有一个函数,它返回从输入列表中找到的半个回文的列表。如果我在一行使用if语句,它会起作用,但我想使用保护。警卫给我一个解析错误。我读了很多给出这种错误的案例,但我没有弄清楚我的案例。这是代码:

palindromeHalfs :: [String] -> [String]
palindromeHalfs xs = map firstHalf (filter palindrome xs)
where
firstHalf :: String -> String
firstHalf ys | (length ys) `rem` 2 == 0 = take ((div (length ys 2)) ys
| otherwise                = take ((div (length ys 2) + 1) ys
palindrome :: String -> Bool
palindrome str | str == reverse str = True
| otherwise          = False 

错误:

palindromeHalfs.hs:6:20: error: parse error on input `otherwise'
|
6 |                  | otherwise                = take ((div (length ys 2) + 1) ys
|                    ^^^^^^^^^

如果我更换,该功能就会工作

firstHalf ys | (length ys) `rem` 2 == 0 = take ((div (length ys 2)) ys
| otherwise                = take ((div (length ys 2) + 1) ys

带有

firstHalf ys = if (length (ys !! 0)) `rem` 2 == 0 then take ((div (length (ys !! 0)) 2)) ys 
else take ((div (length (ys !! 0)) 2) + 1) ys

在我的代码中,if语句是一行,它不适合这里。如果有人能告诉我哪一个更受欢迎,如果还是警卫,我将不胜感激。当然,为什么我的警卫不工作。

括号在中不平衡

take ((div (length ys 2)) ys

至于风格,在可以使用任意一种的情况下,防护装置都比if/else更受欢迎。还要注意,even :: Integral a => a -> Bool是一个存在的函数;你不必用rem来发明它。

最新更新