I've been trying to do an infinite list of powers the same as I done them like below, for a list of fibonacci numbers and factorials.
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
facs = 1 : zipWith (*) [1 ..] facs
Thanks
Generating the powers of a number is as simple as using 'iterate':
iterate (*2) 1
To find a specific power (instead of listing them) it is faster to use (^)
. To see the individual steps of a large multiplication you can use scanl
:
scanl (*) 1 [2, 3, 5, 7]
Finally to generate a list of all squares this is the approach I recommend:
fix (\more r s -> s : more (r + 1) (s + 2*r + 1)) 0 0
Or if you are uncomfortable with fix
here are two alternative versions:
unfoldr (\(r, s) -> Just (s, (r + 1, s + 2*r + 1))) (0, 0)
map snd . iterate (\(r, s) -> (r + 1, s + 2*r + 1)) $ (0, 0)
For greater readability you can also use map
:
List of consecutive powers of 2:
λ> map (2^) [0..10]
[1,2,4,8,16,32,64,128,256,512,1024]
Consecutive squares:
λ> map (^2) [0..10]
[0,1,4,9,16,25,36,49,64,81,100]
I think you can define an infinite sequence of the squares with just a list comprehension:
powers = [ ii*ii | ii <- [1 ..]]
take 10 powers
=> [1,4,9,16,25,36,49,64,81,100]
Edit: It's been explained that you are after the powers of 2, which can also be done with a list comprehension:
powersOf2 = [ 2^ii | ii <- [0 ..]]
take 10 powersOf2
=> [1,2,4,8,16,32,64,128,256,512]
You can extrapolate this to a generator function for any given base:
powersOfN nn = [ nn^ii | ii <- [0 ..]]
take 10 (powersOfN 3)
=> [1,3,9,27,81,243,729,2187,6561,19683]
take 10 (powersOfN 17)
=> [1,17,289,4913,83521,1419857,24137569,410338673,6975757441,118587876497]
powers n = 1 : map (n*) (powers n)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With