gpt4 book ai didi

haskell - 将带有break-s/continue-s的命令式控制流转换为haskell

转载 作者:行者123 更新时间:2023-12-02 18:39:53 24 4
gpt4 key购买 nike

考虑以下命令式代码,该代码在 3 位数字的乘积中查找最大的回文数(是的,这是“[18 世纪杰出数学家]”网站的第一个任务之一):

curmax = 0
for i in range(999,100):
for j in range(999,100):
if ((i*j) < curmax): break
if (pal(i*j)):
curmax = i*j
break
print curmax

由于我目前正在学习 Haskell,我的问题是,你如何翻译这个(以及基本上任何包含比简单迭代更复杂的内容的命令式结构,例如中断、继续、临时变量以及所有这些)到 Haskell?

我的版本是

maxpal i curmax
| i < 100 = curmax
| otherwise = maxpal (i-1) (innerloop 999)
where
innerloop j
| (j < 100) || (p < curmax) = curmax
| pal p = p
| otherwise = innerloop (j-1)
where p = i*j
main = print $ maxpal 999 0

但这看起来我们仍然处于势在必行的丑陋镇。

那么您有什么建议,处理此类 FP 式案例的方法是什么?

最佳答案

与 Daniel 和 sepp2k 的类似答案:

惰性函数式编程使您能够以比您在问题中的命令式控制流中看到的更加模块化的方式编写程序。例如,形成因子列表 999...100,然后是所有乘积,然后过滤以仅保留回文,然后计算最大值。由于惰性,这些中间列表将仅在需要时产生,并且将被增量回收。

更多解释和示例请参见John Hughes的经典论文Why Functional Programming Matters .

maxpal :: Int
maxpal = maximum [i*j | i <- factors, j <- factors, pal (i*j) ]

factors :: [Int]
factors = [999,998..100]

pal :: Show a => a -> Bool
pal = palL . show

palL :: (Eq a) => [a] -> Bool
palL xs = xs == reverse xs

关于haskell - 将带有break-s/continue-s的命令式控制流转换为haskell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4512541/

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