【CS 61a study notes 7】Scheme

Scheme

Scheme is a dialect of Lisp, the second-oldest programming language that is still widely used today.

Scheme python code

https://github.com/reah/scheme_interpreter/tree/master
Notes : this code does not cover all the built-in function in the Scheme ,just use it to do some simple tasks

Special Forms

A combination that is not a call expression is a special form:

  • if expression: ( if <predicate> <consequent> <alternative> )
    • Evaluate the predicate expression
    • Evaluate either the consequent or alternative
  • And and or : ( and <e1> … <e2> ) ,( or <e1> … <e2> )
  • Binding symbols : ( define < symbol > <expression> )
  • New procedures : ( define (< symbol > <formal parameters> ) < body > )
scm> (define (square x) (* x x))
square
# define abs
scm> (define (abs x)
		(if (< x 0)
			(-x)
			x))
abs

# define recursive function in scheme
scm> (define (sqrt x)
		(define (update guess)
			(if (=square guess) x)
				guess
				(update (average guess (/ x guess)))))
		(update 1))
sqrt

lambda expressions

lambda expressions evaluate to anonymous procedures.
( lambda (< formal-parameters >) < body>)

# two equivalent expressioms:
scm> (define (plus4 x) (+ x 4))
scm> (define plus4 (lambda (x) (+ x 4)))

Sierpinski’s Triangle

# forward
scm> (fd 100) 
# backward
scm> (bk 100)
#turn right by an angle 
scm> (rt 90)
#turn left by an angle
scm> (t 90)
# draw a line
(define (line) (fd 50))
# define a repeat function ,k is the repeat times
(define (repeat k fn)
	(fn)
	(if (> k 1)(repeat (-k 1) fn)))	
# define a triangle
(define (tri fn)
	(repeat 3 (lambda () (fn) (lt 120))))
# draw a triangle
scm> (tri line)

### sierpinski's triangle
### sierpinski's triangle has some recursive depth d ,and some side length k
(define (sier d k)
	(tri (lambda () (if (= d 1) (fd k) (leg d k)))))

(define (leg d k)
	(sier (- d 1) (/ k 2)
	(penup) (fd k) (pendown))

scm> (rt 90)
scm> (speed 0)
scm> (sier 5 200)

Cond & Begin

The cond special form that behaves like if-elif-else statements in Python.


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值