gpt4 book ai didi

haskell - 首先分配一些变量后使用 guard

转载 作者:行者123 更新时间:2023-12-02 02:51:21 27 4
gpt4 key购买 nike

我知道我可以做到这一点...

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

这将导致编译错误,但我相信您知道我要做什么。

最佳答案

使用 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

关于haskell - 首先分配一些变量后使用 guard ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5836058/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com