1 Arithmetic 算数
四种原子数据
- numbers
- strings
- boolean values
- images
1.1 The Arithmetic of Numbers
(define x 3)
(define y 4)
(define (square x)(* x x))
(sqrt (+ (square x) (square y)))
-----------------------------------------------------------------------------------
1.2 The Arithmetic of Strings
字符串的拼接,像python中的 str1 + str2
> (string-append "what a " "lovely " "day" " 4 BSL") |
"what a lovely day 4 BSL" |
My code
(define prefix "hello")
(define suffix "world")
(string-append prefix "_" suffix)
--------------------------------------------------------------
1.3 Mixing it Up
Exercise 3. Add the following two lines to the definitions area:
My code:
(define str "helloworld")
(define i 5)
(string-append
(substring str 0 i)
"_"
(substring str i))
Exercise 4. Use the same setup as in exercise 3 to create an expression that deletes the ith position from str. Clearly this expression creates a shorter string than the given one. Which values for i are legitimate?
My code:
(define str "helloworld")
(define i 5)
(string-append
(substring str 0 i)
(substring str (+ i 1)))
----------------------------------------------------------
1.4 The Arithmetic of Images
(require 2htdp/image) 首先导入图形库
circle produces a circle image from a radius, a mode string, and a color string;
ellipse produces an ellipse from two radii, a mode string, and a color string;
line produces a line from two points and a color string;
rectangle produces a rectangle from a width, a height, a mode string, and a color string;
text produces a text image from a string, a font size, and a color string; and
triangle produces an upward-pointing equilateral triangle from a size, a mode string, and a color string.
> (circle 10 "solid" "green") |
> (rectangle 10 20 "solid" "blue") |
> (star 12 "solid" "gray") |
除了绘制图形,还能获取图形参数
image-width determines the width of an image in terms of pixels;
image-height determines the height of an image;
> (image-width (circle 10 "solid" "red")) |
20 |
> (image-height (rectangle 10 20 "solid" "blue")) |
20 |
(+ (image-width (circle 10 "solid" "red")) |
(image-height (rectangle 10 20 "solid" "blue"))) |
40
>
Exercise 6. Add the following line to the definitions area:
(define cat )
Create an expression that counts the number of pixels in the image.
my code:
(require 2htdp/image)
(define cat )
(image-height cat)
(image-width cat)
--------------------------------------------------------
1.5 The Arithmetic of Booleans 逻辑运算符
or
> (or #true #true) |
#true |
> (or #true #false) |
#true |
> (or #false #true) |
#true |
> (or #false #false) |
#false |
and
> (and #true #true) |
#true |
> (and #true #false) |
#false |
> (and #false #true) |
#false |
> (and #false #false) |