本文介绍了在Haskell中制作除数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我在euler项目中做了第21题。 一部分需要找到一个数字的正确因数列表。即剩余 n 和少于 n 的数字。所以我做了这个哈斯克尔,但GHCI对我很生气。 divisors n = [n | n 问题是我不知道如何制作: n `rem` [1..(n-1)] 比 n 平均分配 n 。解决方案 您只需要一个单独的变量。 Prelude>让除数n = [x | x Prelude>除数20 [1,2,4,5,10] 前奏>除数30 [1,2,3,5,6,10,15] 现在,如果你想提高效率,我们已经知道除数不会超过 n 的一半,我们知道1是除数一切。而且,让我们继续,让Haskell-y多一点,以避免列表理解:让除数n = 1:filter((== 0)。rem n)[2 .. n`div` 2] Prelude>除数20 [1,2,4,5,10] 前奏>除数30 [1,2,3,5,6,10,15] 前奏>除数31 [1] I am doing problem 21 in eulerproject.One part requires finding the list of proper divisors of a number. i.e. where there is remainder of n and some number of less than n. So I made this Haskell, but GHCI gets angry at me.divisors n =[ n | n <- [1..(n-1)], n `rem` [1..(n-1)] ==0 ]The problem is that I don't know how to make:n `rem` [1..(n-1)]so that it only returns the number less than n that divide evenly into n. 解决方案 You just need a separate variable.Prelude> let divisors n = [x | x <- [1..(n-1)], n `rem` x == 0]Prelude> divisors 20[1,2,4,5,10]Prelude> divisors 30[1,2,3,5,6,10,15]Now, if you wanted to make it a bit more efficient, we already know that a divisor won't be more than half of n, and we know 1 is a divisor of everything. And, let's go ahead and make it a bit more Haskell-y to boot, avoiding a list comprehension:Prelude> let divisors n = 1 : filter ((==0) . rem n) [2 .. n `div` 2]Prelude> divisors 20[1,2,4,5,10]Prelude> divisors 30[1,2,3,5,6,10,15]Prelude> divisors 31[1] 这篇关于在Haskell中制作除数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-23 06:02