Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get an infinite list of powers using the below methods in haskell

Tags:

haskell

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

like image 931
lakers2012 Avatar asked Nov 18 '12 16:11

lakers2012


4 Answers

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)
like image 92
ertes Avatar answered Sep 28 '22 07:09

ertes


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]
like image 44
w.b Avatar answered Sep 28 '22 06:09

w.b


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]
like image 44
Kyle Burton Avatar answered Sep 28 '22 08:09

Kyle Burton


powers n = 1 : map (n*) (powers n)
like image 21
josejuan Avatar answered Sep 28 '22 06:09

josejuan