fornit
fornit

Reputation: 79

How is this infinite list computed?

The problem is the following:

Define a Haskell variable dollars that is the infinite list of amounts of money you have every year, assuming you start with $100 and get paid 5% interest, compounded yearly. (Ignore inflation, deflation, taxes, bailouts, the possibility of total economic collapse, and other such details.) So dollars should be equal to: [100.0, 105.0, 110.25, ...].

My solution is the following and it works:

 dollars::[Double]
 dollars = 100.0 : [1.05 * x | x<- dollars ] 

The problem is that I have trouble understanding how the list is computed practically:

dollars= 100.0 : [1.05 * x | x<- dollars ] 
= 100.0 : [1.05 * x | x<- 100.0 : [1.05 * x | x<- dollars ]   ]
= 100.0 : (1.05 * 100.0) : [1.05 * x | x<- [1.05 * x | x<- dollars ]    ]
= 100.0 : 105.0 : [1.05 * x | x<- [1.05 * x | x<- dollars ]   ]
= 100.0 : 105.0 : [1.05 * x | x<- [1.05 * x | x<-  100.0 : [1.05 * x | x<- dollars ]  ]  ]
= 100.0 : 105.0 : [1.05 * x | x<- 105.0:[1.05 * x | x<-[1.05 * x | x<- dollars ]  ]  ]
= 100.0 : 105.0 : 110.25 :[1.05 * x | x<-[1.05 * x | x<-[1.05 * x | x<- dollars ]  ]  ]

etc.

Is that how it is computed? If not then how? If yes, is there a simpler way to conceptualize these kinds of computations?

Upvotes: 1

Views: 84

Answers (2)

Paul Johnson
Paul Johnson

Reputation: 17786

You are pretty much correct. It might help if you de-sugared the list comprehension into a function call. The equivalent is

dollars = 100.0 : map (* 1.05) dollars

This then evaluates to

= 100.0 : let dollars1 = 100 * 1.05 : map (*1.05) dollars1 in dollars1
= 100.0 : 105.0 : let dollars2 = 105 * 1.05 : map (*1.05) dollars2 in dollars2

and so on. I'm using dollars1, dollars2 as identifiers, even though they don't really exist.

Upvotes: 2

jmg
jmg

Reputation: 7404

That is more or less correct. In which order the substitutions happen depends on the code that prints out the results. The substitutions in the 2. and 3. line could be swapped.

Upvotes: 0

Related Questions