Skip to content

Learning Scheme

OK, so my new mini project is to learn Scheme. It can't be too hard, right? I mean Javascript is just Lisp in C's clothing, and I'm good at Javascript. I've installed PLT-Scheme and I figure the best way to learn it is solving Project Euler problems until I get bored.

Problem 1:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

Translating Javascript to Scheme means function(x, y) {foo;bar;} becomes (lambda (x y) (foo) (bar)) and var x = y; becomes (define x y) and realizing that all loops have to be made into tail-recursive function calls gives us this pretty easily:

(define divides
  (lambda (a b)
    (= 0 (remainder b a))))

(define euler1
  (lambda (n)
      ((= n 1) 
      ((or (divides 5 n) (divides 3 n))
        (+ n (euler1 (- n 1))))
      (else (euler1 (- n 1))))))

(euler1 999)

And the correct answer is 233168. Not bad for my first Scheme program! (Certainly more interesting than (display "hello, world")).

Addendum: I just looked at the forum at Project Euler and I see that there's a much better solution; just add the series 3+6+9....999, which is simply 3*(1+2+3+...333) or 3* 333 * (333+1)/2, to the series 5+10+15+...995, or 5 * 199 * (199+1)/2 and subtract the series 15+30+45... which is counted twice. No loops! Less interesting for learning to program, though.

{ 2 } Comments

  1. Rupesh Tiwari | November 20, 2010 at 11:54 pm | Permalink

    Hi Danny,

    I quite impressed with your knowledge in javascript and Scheme.

    You have learned Scheme. I read the Doug’s article that learning Scheme will improve the knowledge of JavaScript and whatever we can do in Scheme is possible in JavaScript also.

    I just wanted to ask you that how Scheme is helping you to improve your JavaScript knowledge ?

    Can you write something on that. I believe that will be helpful, and it will encourage me too learn Scheme. I don’t know any thing about Scheme!! :(

  2. Danny | November 21, 2010 at 3:35 pm | Permalink

    While I suppose learning Scheme may help learn the functional programming aspects of Javascript (closures and anonymous functions, called lamdba functions in Scheme), you’re probably better off learning and playing with them in Javascript directly. I was working on learning Scheme because it’s used in gnuCash, which I just started using. Not directly connected to my Javascript work.

Post a Comment

Your email is never published nor shared. Required fields are marked *