ผลต่างระหว่างรุ่นของ "Racket"

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา
แถว 30: แถว 30:
  
 
=== define ===
 
=== define ===
 +
ตัวอย่าง
 +
 +
(define (inc x)
 +
  (+ x 1))
 +
(define (dec x)
 +
  (- x 1))
 +
(define (square x)
 +
  (* x x))
  
 
=== if ===
 
=== if ===

รุ่นแก้ไขเมื่อ 02:43, 15 ตุลาคม 2557

ภาษา

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

lambda

list

local variables: let, let*

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

Useful functions

  • null?, list?
  • empty
  • first, rest
  • list, cons

แบบฝึกหัด 1

1. mylen

2. mymax

3. myappend

4. myreverse

5. myconcat

6. myslice

7. myexpand

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

8. mycascade

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

9. myflatten

Tail recursion

Data structures

ท่าพื้นฐาน

functional programming

filter, map, fold

แบบฝึกหัด 2