免责声明:我是Haskell的新手,我不记得很多关于大学的FP,所以我的代码中可能有一两个以上的错误.这也是我的欧拉问题3的代码.
我试图递归调用一个函数,其中两个数组作为参数,一个数组作为结果.
目标:
这是我的代码:
mkList :: Int -> [Int]
mkList n = [1..n-1]
modArray :: Int -> Int -> [Int]
modArray a b = [ x*b | x <- [1..a], x `mod` b == 0]
modArrayAll :: [Int] -> [Int] -> [Int]
modArrayAll [] [] = []
modArrayAll (x:xs) (y:ys) = (e)
where
m = head( ys)
n = length( xs)
e = (modArrayAll xs ys ) \\ modArray n m
Run Code Online (Sandbox Code Playgroud)
(主要)
let allNumbers = mkList (first + 1)
let allFactors = mkList (first + 1)
let mainList2 = modArrayAll allNumbers allFactors
Run Code Online (Sandbox Code Playgroud)
这导致空列表.但是,如果我有:
e = xs \\ modArray n m --WORKS for one iteration
Run Code Online (Sandbox Code Playgroud)
我从1到10得到所有奇数.
我的问题:为什么这不按我期望的方式工作?我希望递归堆栈会达到空数组条件并返回一个空数组,该数组不会从调用数组中删除,它会继续只返回素数?
我复制了你的目标说明:
-- assume n is 10 for this question
n=10
-- create a list of all natural numbers from 1 to n (variable is 'allNumbers' is code)
allNumbers = [1..n]
-- create another list of all natural numbers from 1 to n (variable is 'allFactors' is code)
allFactors = [2..n] -- i suspect you really wanted this rather than [1..n]
-- take the first element in 'allFactors' and
-- multiply the rest of the numbers of 'allFactors' by this number.
-- (this generates an array of numbers)
-- continue from 1 to n until 'allFactors' is empty
factorProducts = [ x*y | x <- allFactors, y <- allFactors]
-- remove all these numbers from 'allNumbers'
whatYouWanted = allNumbers \\ factorProducts
Run Code Online (Sandbox Code Playgroud)
目前你似乎还在思考一个相当强制性的思维模式.尝试更多地考虑你想要的东西,而不是如何得到它:)