【发布时间】:2020-04-17 19:43:34
【问题描述】:
最近几周我刚刚开始学习 Haskell。我正在使用 Project Euler 问题来学习,目前正在尝试找出是否可行。不是找人给我答案,只需要帮助理解 Haskell 中的数据结构。
我目前正在研究problem 484,它指定了一个递归函数。编写函数不是问题,我目前有:
import Math.NumberTheory.Primes
import Data.Maybe
import Data.List
derivative :: Integer -> Integer
derivative x
| x < 2 = error "Error: Attempt to evaluate outside domain"
| isPrime x = 1
| otherwise = (derivative a)*b + a*(derivative b)
where
[a, b] = int_split x
--this function find the first pair of divisors
int_split :: Integer -> [Integer]
int_split n = [first_div, n `div` first_div] where
first_div = fromJust $ find (\x -> (n `mod` x) ==0) [2..]
这似乎工作正常,因为计算与问题给出的样本值相匹配。问题是我需要为非常大的值计算这个,通过 5x10^15 获取所有值。将所有值提高到 ~10^8 运行得非常快,但超过了它就会变得很慢。简单地使用 map 肯定是低效的,因为它没有利用我们可以引用以前计算的值这一事实。
我的想法是更改我的函数以将值存储在查找表中,因为它们被计算为函数能够引用。我尝试使用 Data.Map 来存储值,但我不知道如何以递归方式将其集成到我的函数中。这在 Haskell 中可行吗?或者有没有更好的方法来存储和使用中间计算?
【问题讨论】:
-
查找“memoization”,你应该找到几个例子。
-
感谢您的建议,只是不知道该查找什么!我的数学背景比较强,所以我对其中一些概念有点陌生。