递归函数的空列表 [英] empty list on recursive function

查看:129
本文介绍了递归函数的空列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着在上寻求一些乐趣,但我现在被困在一个问题上,想要继续前进但似乎不能让我的功能工作。我试图计算给定整数的主因子。该功能适用​​于较小的数字,如13195:

 > primeFactor 13195 
[29,13,7,5]

但是当我运行更大号码,例如600851475143:

 > primeFactor 601851475143 
[]

这对我来说似乎很奇怪。我知道haskell是一种懒惰的语言,但我不认为它应该是懒惰的...

  primeFactor':: Int  - > [Int] 
primeFactor'n = [p | p 其中素数':: [Int] - > [Int] - > [Int]
primes'ys [] = ys
primes'ys(x:xs)| x`notMultipleOf` ys = primes'(x:ys)xs
|否则= primes'ys xs

- 辅助函数到primeFactor'
notMultipleOf :: Int - > [Int] - > Bool
notMultipleOf n [] = True
notMultipleOf n xs = and [n`mod` x / = 0 | x < - xs]


解决方案

Int 有32位,您不能存储该数字(使用 Integer )。



<另一方面,您可以使用 Data.Numbers.Primes (和
查看代码):

 > primeFactors 601851475143 
[3,3,23,1009,2881561]
> primeFactors 600851475143
[71,839,1471,6857]


Im trying do some work on Project Euler for fun, but I got stuck now on an problem and want to move on but cant seem to get my function working. Im trying to get count the primefactors of a given integer. The function works on smaller numbers such as 13195:

> primeFactor 13195
[29,13,7,5]

But when I run a bigger number such as 600851475143:

> primeFactor 601851475143
[] 

This seems really weird to me. I know haskell is a lazy language, but I don´t think it should be that lazy...

primeFactor' :: Int -> [Int]
primeFactor' n = [ p | p <- primes' [] [2 .. n], n `mod` p == 0 ]
   where primes' :: [Int] -> [Int] -> [Int]
         primes' ys [] = ys
         primes' ys (x:xs) | x `notMultipleOf` ys = primes' (x:ys) xs
                           | otherwise            = primes' ys xs                                                                                         

-- helper function to primeFactor'
notMultipleOf :: Int -> [Int] -> Bool
notMultipleOf n [] = True
notMultipleOf n xs = and [n `mod` x /= 0 | x <- xs]

解决方案

Int has 32 bits you can't store that number (use Integer).

On the other hand, you can use Data.Numbers.Primes (and see code):

> primeFactors 601851475143
[3,3,23,1009,2881561]
> primeFactors 600851475143
[71,839,1471,6857]

这篇关于递归函数的空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆