reset password
Author Message
rabbott
Posts: 1649
Posted 12:48 Oct 19, 2017 |

I've modified the definition of the while function so that it now has four parameters instead of three.

init state                                    -- Initialize the state.

while (shouldContinue state)   -- while some condition holds on the state,

{                                                -- run the body of the loop on the state

  bodyFn state                          -- producing a new state.

}                                               -- (The new parameter) Return a result extracted from the final value of the state.

The type is now as follows.

while :: state ->              -- The initial value of the state

         (state -> Bool) ->   -- A shouldContinue test

         (state -> state) ->  -- A bodyFn

         (state -> result ->  -- A function to build the final value (the new parameter)

         result                   -- The return value

 

The nSquares function now looks like this.

nSquares:: Int -> [Int]

nSquares n =

    while (1, [])

             (\(index, _) -> index <= n) -- n is the nSquares argument.

             (\(index, list) -> (index + 1, index^2 : list))

             (reverse . snd)   -- Previously, this had been applied to the output of the while function.

                                       -- Now it is passed to the function, which applies it at the end.

If you want to return the final value of the state unmodified, use the id function as the fourth parameter.

You may stay with the 3-parameter version or switch to the 4-parameter version. 

If you have already done project 3, there is no need to do anything.