码迷,mamicode.com
首页 > 其他好文 > 详细

Scheme初探

时间:2015-07-16 00:39:59      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

Scheme programs consist of expressions( everything is expressions ), which can be:
  •Primitive expressions: 2, 3.3, true, +, quotient, ...
  •Combinations: (quotient 10 2), (not true), ...

 

1. Primative expressions

Numbers are self-evaluating; symbols(just like name in Python) are bound to values

scm> 123
123
scm> 123.123
123.123
scm> #t
#t
scm> #f
#f
scm> "asdf"
"asdf"
scm> ’a ; this is a symbol
a

when you use the single quote, you’re telling Scheme not to follow the normal rules of evaluation and just have the symbol return as itself. 

 

2. Function Calls
Call expressions include an operator and 0 or more operands in parentheses

scm> (+ 1 2)
3
scm> (- 2 3)
-1
scm> (* 6 3)
18
scm> (/ 5 2)
2.5
scm> (+ 1 (* 3 4))
13

 some userful functions

+, -, *, /
• eq?, =, >, >=, <, <=

 

3. Special forms

A combination that is not a call expression is a special form:
  • if expression: (if <condition> <then> <else>)
  • and  or not: (and <e1> ... <en>), (or <e1> ... <en>), (not <en>)
  • Binding symbols: (define <symbol> <expression>)
  • New procedures: (define (<symbol> <formal parameters>) <body>)

scm> (if ’this-evaluates-to-true 1 2)
1
scm> (and 1 2 3)
3
scm> (or 1 2 3)
1

 

 Defining functions

scm> (define (square x) (* x x))
square
scm> (square 5)
25

 

Lambda Expressions
Lambda expressions evaluate to anonymous procedures
  (lambda (<formal-parameters>) <body>)
Two equivalent expressions:

(define (plus4 x) (+ x 4))
(define plus4 (lambda (x) (+ x 4)))

Ps:When you do (define ( ) ), Scheme will automatically transform it to (define (lambda () ). In this way, lambdas are more central to Scheme than they are to Python. 

 

4. Compound values
Pairs and Lists
  • cons: Two-argument procedure that creates a pair
  • car: Procedure that returns the first element of a pair
  • cdr: Procedure that returns the second element of a pair
  • nil: The empty list

Pairs

> (define x (cons 1 2))
> x
(1 . 2)   #Dots can be used in a quoted list to specify the second element of the final pair.
> (car x)
1
> (cdr x)Dots can be used in a quoted list to specify the second element of the final pair.
2
> (cons 1 (cons 2 (cons 3 (cons 4 nil))))
(1 2 3 4)

 List

scm> ’()
()
scm> nil
()
scm> (cons 1 (cons 2 nil))
(1 2)
scm> (cons 1 (cons 2 (cons 3 nil)))
(1 2 3)
scm> ’(1 2 3)
(1 2 3)

 

5. Symbolic Programming

Symbols normally refer to values

> (define a 1)
> (define b 2)
> (list a b)
(1 2)

Quotation is used to refer to symbols directly in Lisp.

> (list ‘a ‘b)
(a b)
> (list ‘a b)
(a 2)

Quotation can also be applied to combinations to form lists.

 > (car ‘(a b c))
 a
 > (cdr ‘(a b c))
 (b c)

 

 

Ps:scheme 中没有while, for等, 所有要用到迭代的地方都用递归

 

2015-07-15

Scheme初探

标签:

原文地址:http://www.cnblogs.com/whuyt/p/4649791.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!