JavaScript and SiC

Source: Internet
Author: User
Tags square root

In the past two days, the company's project has come to an end, and the school's homework is not too difficult. So I had a little leisure time, So I re-read SiCp and learned JavaScript at the same time (I saw Google suggest, Google Maps, and canyonbridge cbconnect, so I had a strong interest in Javascript ). Douglas crockford spoke well. JavaScript does have many similarities with scheme. Javascript authors must be familiar with function programming. Otherwise, it would be a coincidence that JavaScript Functions are lambda operators. For example, the Newton-Raphson algorithm used to calculate the square root in sicp1.1:

(Define (sqrt x)
(Define (good-enough? Guess)
(<(ABS (-(square guess) x) 0.001 ))
(Define (improve guess)
(Average guess (/X guess )))
(Define (SQRT-iter guess)
(If (good-enough? Guess)
Guess
(SQRT-ITER (improve guess ))))
(SQRT-iter 1.0 ))

The javascript version is almost mechanical:

// Newton's method to find/SQRT {x}
Function SQRT (x ){
Function sqrt_iter (guess ){
If (good_enough (guess )){
Return guess;
}
 
Return sqrt_iter (improve (guess ));
}

Function improve (guess ){
Return average (guess, X/guess );
}

Function average (x, y ){
Return (x + y)/2;
}

Function good_enough (guess ){
Return math. Abs (guess * Guess-x) <0.001;
}

Return sqrt_iter (1.0 );
}

Well, it seems that it is also interesting to rewrite the program in with JavaScript.

Well, it seems that it is also interesting to rewrite the program in with JavaScript.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.