第 2 部分 · 高级特性
模式匹配
模式匹配
使用 match 表达式优雅地解构和处理数据。
match 基础
#lang racket (require racket/match) (define (describe x) (match x [0 "zero"] [1 "one"] [(? string?) "a string"] [(? number?) "a number"] [_ "something else"])) (describe 0) ; => "zero" (describe "hello") ; => "a string" (describe '(1 2)) ; => "something else"
解构列表
(define (head-tail lst) (match lst ['() "empty"] [(list x) (format "one element: ~a" x)] [(list x y) (format "two elements: ~a and ~a" x y)] [(list x xs ...) (format "first: ~a, rest: ~a" x xs)])) (head-tail '()) ; => "empty" (head-tail '(1)) ; => "one element: 1" (head-tail '(1 2)) ; => "two elements: 1 and 2" (head-tail '(1 2 3)) ; => "first: 1, rest: (2 3)"
解构结构体
(struct point (x y) #:transparent) (define (quadrant p) (match p [(point 0 0) "origin"] [(point x 0) (format "on x-axis at ~a" x)] [(point 0 y) (format "on y-axis at ~a" y)] [(point x y) (format "(~a, ~a)" x y)]))
守卫条件
(define (classify n) (match n [(? (lambda (x) (> x 0))) "positive"] [(? (lambda (x) (< x 0))) "negative"] [_ "zero"]))
小结
模式匹配让数据解构变得直观和安全。它是替代嵌套 if 和 cond 的利器。