Reputation: 4379
I am confused why my function nest
which composes f
with itself n
times
nest f 0 = id
nest f n = f . nest f (n - 1)
never terminates. I would have thought that it would "pattern match" on the case when n
becomes zero. I am defining it by typing these two lines into GHCI and calling with nest (+ 1) 2 3
for instance.
Upvotes: 7
Views: 200
Reputation: 64740
When you pasted it into GHCi what you did was define one function of nest f 0 = id
. Then you said "ignore that function, I'm replacing it with a new function of the same name where the whole definition is nest f n = f . nest f (n - 1)
.
Upvotes: 6
Reputation: 1096
By typing the function on two separate REPL lines, you are essentially redefining it the second time around, omitting the base case.
The correct way to enter this function into the REPL is:
nest f 0 = id; nest f n = f . nest f (n - 1)
Alternatively, you can enter multiline mode with the :{
command, and leave it using :}
.
Upvotes: 11