Functional programing with DrScheme

15 Feb 2008

First of all i am thanking my guru Mr.Pramod .C.E , for his article in Linux Gazette from where i got the idea of DrScheme. DrScheme is an interactive, integrated, graphical programming environment for the Scheme, a functional programming language,which is similar to LISP.

Drscheme can be downloaded and Installed from A script will be available there, running which will install DrScheme and along with it, pl- games (some games in Scheme), scheme web server etc.

Now run the command "drscheme" , to start the program. Then choose scheme as our language. Try the basic built in functions like + , -,* etc. Then try writing custom functions like factorial.

DrScheme is an excellent tool for learning programming.For a beginner it will be very easy to go deeply into recursive function executions using the built in "stepper". For using the stepper you need to change the mode as "intermediate student" in the Language menu.Now you will have the STEPPING button on the window, with which you can trace your function execution, and will be able to understand how control is moving in your code.This can be very helpful for a beginner in functional programming.

Language menu can set high privileges like advanced student option , so that we have the flexibility to define functions like this


(define (my-cube x) (* x x x)) (define (fun f x) (f x)) (fun my-cube 3)

here fun will replace f as my-cube function with a argument of 3 and returns you 27

We can also use lambda ie to call anonymous functions and define local variables inside a function.

Ex (define (fun x y) (let ((p (* x y)) (q (+ x y))) (* p q)))

(fun 2 3) ; evaluates to 30 The general syntax of ‘let’ is:

(let ( (var1 exprn1) (var2 exprn2) ... (varn exprn) ) body)

The three fundamental operations on a list are car, cdr and cons. Let try it in scheme.

(define a (list 1 2 3 4)) ; create a list (1 2 3 4) and bind it to ‘a’ (define b '(1 2 3 4 5)) ; same as above; note the use of the quote (empty? b) ; returns false '() ; empty list (cons 1 '(2 3 4)) ; yields '(1 2 3 4) (car '(4 1 2 3)) ; yields 4 (first '(1 2 3)) ; yields 1 (cdr '(1 4 2 3)) ; yields '(4 2 3) (rest '(1 2 3)) ; yields'(2 3) Bit of graphics We can move on to simple graphic functions by loading teaching packs such as , etc .Here we can write small code fragment to draw a line .


(start 100 100) ; opens a window (define p (make-posn 0 0)) ; creates a ‘posn’ structure (define q (make-posn 50 50)) (draw-solid-line p q 'blue) ; which will draw a line from p to q in color blue

Also we can simulate a game called The Chaos Game , to get code for this click here program Here is the screen shot of it. chaosgame

Also i wished to do some turtle graphics programming stuffs in scheme but unfortunately i couldn't able to load the library ( successfully. Hope i can do it next time :)