I'm going to transform a scheme program into Haskell but I'm having a hard time learning all about Haskell. If you are familiar with SICP, I`m tasked to answer Exercises 3.63, 3.64, 3.65, 3.66 and 3.71. I have already found the answers to these problems but they are written in scheme. Here is the question and answer in 3.63:
Exercise 3.63. Louis Reasoner asks why the sqrt-stream procedure was not written in the following more straightforward way, without the local variable guesses:
(define (sqrt-stream x) (cons-stream 1.0 (stream-map (lambda (guess) (sqrt-improve guess x)) (sqrt-stream x))))Alyssa P. Hacker replies that this version of the procedure is considerably less efficient because it performs redundant computation.
Explain Alyssa's answer.
Would the two versions still differ in efficiency if our implementation of delay used only
(lambda () <exp>)without using the optimization provided by memo-proc (section 3.5.1)?
Answer:
In Louis Reasoner’s procedure,
(sqrt-stream x)is recursively called inside(sqrt-stream x). However, the two streams are not the same variable. Therefore redundant computation is performed. In the original version, a local variable guesses is used.(define (sqrt-stream x) (define guesses (cons-stream 1.0 (stream-map (lambda (guess) (sqrt-improve guess x)) guesses))) guesses) (display-stream (sqrt-stream 2))
Here is the Haskell code that I wrote and it's not working:
module Main
where
guess = 1:: Double
x=0
do
if ((guess*guess) = x)
then y = (x + guess) / x
guess = y
else
sqrt x = guess
Please help me fix my codes. I need them next week.
I'll also try the other ones and post them here if there there will be errors again. Hope you can help me.Thanks a lot.
sqrt-improve? - kennytm