James Hamish
James Hamish

Reputation: 105

Iterate Calculation in Haskell

I am a beginner to Haskell, I am trying to create an infinite list in haskell where the next term is found by the following formula

xn+1 = (xn + const / xn) div 2.

I have been looking into the iterate command as I want to apply the same function again to generate the next answer.

I will then use take to choose a certain number of elements from the list.

However I am unsure how I can represent xn when using iterate.

I started writing take 10 (iterate (xn +5 /xn div 2) 1), I know I need to replace the xn but not sure what with.

Could somebody advise me?

Upvotes: 0

Views: 141

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476624

You basically describe a function:

next xn = (xn + c) / (2*xn)

with c the const (const is a function from the Prelude, so do not use that name). Or as a lambda expression:

\xn -> (xn + c) / (2*xn)

with c your constant. So now we can inject that in the iterate:

take 10 (iterate (\xn -> (xn + 5) / (2*xn)) 1)

with c=5, we get:

Prelude> take 10 (iterate (\xn -> (xn + 5) / (2*xn)) 1)
[1.0,3.0,1.3333333333333333,2.375,1.5526315789473684,2.110169491525424,1.684738955823293,1.9839094159713946,1.7601381796335236,1.9203430326819695]

If you want to calculate values over integers, you can use:

\xn -> div (xn + c) (2*xn)

this produces:

Prelude> take 10 (iterate (\xn -> div (xn + 5) (2*xn)) 1)
[1,3,1,3,1,3,1,3,1,3]

If you want to round down the result after the calculation, you can use floor:

\xn -> floor ((fromIntegral xn + 5) / (2* fromIntegral xn))

this produces:

Prelude> take 10 $ iterate (\xn -> floor ((fromIntegral xn + 5) / (2* fromIntegral xn))) 1
[1,3,1,3,1,3,1,3,1,3]

Upvotes: 2

Netwave
Netwave

Reputation: 42698

Just use a lambda function:

mySeq = iterate (\xn ->(xn + 5 `div` xn) `div` 2) 1

Here you have a live example

Upvotes: 2

Related Questions