2011-04-29 33 views
4

我知道我能做到这一点...使用警卫分配一些第一

isZero :: Int -> Bool 
isZero x 
    | x == 0  = True 
    | otherwise = False 

但我可以做这样的事情后的变量?

isPalindrome :: Int -> Bool 
isPalindrome x 
    let digitList = intToDigits x -- Decomposes the integer into 
           -- digits, i.e. 37 -> [3, 7] 
    | digitList == reverse digitList    = True 
    | otherwise          = False 

这会导致编译错误,但我相信你知道我在做什么。

+0

使用语言的条件表达式(“if/then/else”,case语句或警卫)返回“Bool”通常意味着有一个等值ent单个表达式,计算出正确的'Bool'。 – 2011-04-30 02:06:29

回答

14

使用where条款,而不是

isPalindrome :: Int -> Bool 
isPalindrome x 
    | digitList == reverse digitList = True 
    | otherwise      = False 
    where digitList = intToDigits x 

当然,在这个例子中,我们可以只跳过警卫和写

isPalindrome x = digitList == reverse digitList 
    where digitList = intToDigits x 
+1

奖励:由于Haskell是惰性的,因此where子句中的语句只有在其中一个警卫需要时才会被评估。例如(与您的特定问题无关),第一个警卫可以捕获空列表条件,后面的警卫可以依赖where-clause表达式在空列表上出错。 – 2011-04-30 02:09:19

3

为什么不

isPalindrome x = digitList == reverse digitList 
    where digitList = intToDigits x