【发布时间】:2015-09-13 15:25:18
【问题描述】:
这是Question 14。
import Data.Array
import Data.List
import Data.Ord (comparing)
syrs n = a
where
-- For those who don't want to lookup array in the reference
-- the following line creates an array indexed from 1 to n
-- using the list provided. And a ! x is the syntax for a[x] in some other languages.
a = listArray (1,n) $ 0 : [1 + syr n x | x <- [2..n]] -------- 2
syr n x = if x' <= n -------- 1
then a ! x' -------- 1
else 1 + syr n x'
where
x' = if even x
then x `div` 2
else 3 * x + 1
main = print $ maximumBy (comparing snd) $ assocs $ syrs 1000000
以上是Project Euler Q14 on wiki.haskell.org 的建议解决方案。该算法与我的算法基本相同(但我的算法永远运行,而它在 2 秒内运行)。
问题:
在第 2 行,它调用syr n x。假设x = 3,x' = 10,10 < n,它将继续then子句:a ! 10。但此时,a ! 10 尚未计算。那么程序如何进行呢?
【问题讨论】:
-
你想整理一下这种格式吗?我认为没有多少人可以阅读它...
-
@AJFarmar 我应该如何整理格式?代码前的问题?
-
如果它是有效的haskell 代码,那就太好了,但我想我现在可以为你做。我先编辑一下。
-
我猜他说的是缩进。但我也会简化代码并删除“a”:我会说
syrs n = listArray (1,n) ... -
请完整发布您自己的损坏代码。阅读代码时很难进行心理多重搜索/替换。
标签: haskell lazy-evaluation memoization