Racket

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา

ภาษา

Racket เป็นลูกหลานหนึ่งของภาษา LISP อ่านรายละเอียดเพิ่มเติมได้ที่ เอกสาร scheme

REPL

ส่วนล่างของจอ จะเป็น read-eval-print-loop คือพิมพ์ expression เข้าไป ระบบจะอ่าน คำนวณแล้วก็พิมพ์คำตอบ เช่น

> 5
5
> (+ 10 5)
15
> "hello"
"hello"
> (substring "hello" 1 3)
"el"
> (+ (* 4 5) 2)
22

ไวยากรณ์พื้นฐานของภาษา Racket คือการเรียกฟังก์ชัน:

(ฟังก์ชัน อาร์กิวเมนท์1 อาร์กิวเมนท์2 ...)

เราจะไม่สามารถเขียนวงเล็บเล่น ๆ ได้เลย เช่น ถ้าสั่ง (5) จะได้ error ดังนี้

> (5)
. . application: not a procedure;
 expected a procedure that can be applied to arguments
  given: 5
  arguments...: [none]

define

ตัวอย่าง

(define (inc x)
  (+ x 1))
(define (dec x)
  (- x 1))
(define (square x)
  (* x x))

if

(define (myadd a b)
  (if (= b 0)
      a
      (myadd (inc a) (dec b))))

lambda

list

การใช้ quote (') ถ้าใช้เครื่องหมาย single quote (') นำหน้า Racket จะไม่ evaluate list นั้น

> (1 2 3 4)
. . application: not a procedure;
 expected a procedure that can be applied to arguments
  given: 1
  arguments...:
   2
   3
   4
> '(1 2 3 4)
'(1 2 3 4)
(define (mylen lst)
  (if (null? lst)
      0
      (+ 1
         (mylen (rest lst)))))

local variables: let, let*

(define (f x)
  (let ([x1 (+ x 1)]
        [x2 (+ x 2)])
    (+ x1 x2)))

Useful functions

  • null?, list?, equal?
> (null? '(1))
#f
> (null? '())
#t
> (list? 1)
#f
> (list? '(1 2 3))
#t
> empty
'()
> (equal? '() empty)
#t
  • first, rest
> (define lst '(1 2 3 4 5))
> (first lst)
1
> (rest lst)
'(2 3 4 5)
> (first (rest lst))
2
  • list, cons
> (list 1 2 3)
'(1 2 3)
> (list '(1 2 3) 4 5 6)
'((1 2 3) 4 5 6)
> (cons 1 '(2 3 4))
'(1 2 3 4)
> (cons '(1 2) '(3 4 5))
'((1 2) 3 4 5)

แบบฝึกหัด 1

1. mysum

> (mysum '(1 2 3))
6

2. mymax

> (mymax '(1 2 3 -1))
3

3. myappend

> (myappend '(1 2 3 4) 100)
'(1 2 3 4 100)

4. myreverse

> (myreverse '(1 2 3 4))
'(4 3 2 1)

5. myconcat

> (myconcat '(1 2 3 4) '(10 20 30))
'(1 2 3 4 10 20 30)

6. myslice

> (myslice '(1 2 3 4 5 6 7) 3 6)
'(4 5 6)

7. myrange

> (myrange 5 10)
'(5 6 7 8 9)

8. mycascade

> (mycascade '(1 2 3 4 5 6))
'(1 (2 (3 (4 (5 (6))))))

9. myflatten

> (myflatten '(1 (2 3) 4 (5 (6 7))))
'(1 2 3 4 5 6 7)

Tail recursion

(define (fact1 n x)
  (if (= n 0)
      x
      (fact1 (- n 1)
             (* n x))))

(define (fact n)
  (fact1 n 1))

Data structures

ท่าพื้นฐาน

functional programming

filter, map, fold

แบบฝึกหัด 2