Bỏ qua đến nội dung

BP11 - Máy Tính Mini (Interpreter) - Học Design Pattern Từ Những Thứ Đơn Giản

Biến biểu thức lồng nhau như (x + 10) - (y + 2) thành cây cú pháp tự tính toán kết quả theo từng ngữ cảnh. Học mẫu Interpreter trong Python.

Hoang Yell
Hoang Yell
5 phút đọc
English
BP11 - Máy Tính Mini (Interpreter) - Học Design Pattern Từ Những Thứ Đơn Giản

Máy Tính Mini (Interpreter) là một mẫu thiết kế nhóm Behavioral: 🖤🖤🤍🤍🤍 (Độ hữu dụng trong Python: 2/5)

Máy Tính Mini (Interpreter) là gì?

Interpreter gán cho từng thành phần trong một ngôn ngữ nhỏ (hoặc bộ quy tắc) một class riêng để cả biểu thức có thể tự đệ quy tính ra kết quả dựa trên dictionary context.

Ví dụ bạn muốn tính biểu thức (x + 10) - (y + 2) với x = 5, y = 3:

  • Terminal expression (nút lá) (Number, Variable): trả thẳng giá trị số hoặc tra tên biến trong context.
  • Non-terminal expression (nút nhánh) (Add, Subtract): gọi .interpret(context) ở hai nhánh trái/phải rồi cộng hoặc trừ lại.

Tại sao dùng Interpreter?

  • Xử lý lồng nhau sạch sẽ: Khi đã dựng thành cây biểu thức (AST), các phép tính lồng nhiều tầng ngoặc ((x + 10) - (y + 2)) tự giải mượt mà, không vỡ như cắt chuỗi split().
  • Dễ thêm phép toán mới: Muốn thêm phép nhân Multiply chỉ cần viết thêm đúng một class mới mà không đụng vào Add hay Subtract.
  • Đánh đổi: Mỗi quy tắc ngữ pháp đẻ ra một class. Nếu ngôn ngữ phình to quá vài chục luật, đống class Interpreter sẽ trở nên nặng nề khó bảo trì.

Hỏi: Tôi ghét Interpreter, trong Python dùng gì thay thế?

Đáp: Ngoài đời thực, dev Python hiếm khi viết tay cả dàn class Interpreter kiểu GoF. Nếu chỉ đọc literal Python an toàn thì dùng ast.literal_eval(). Còn nếu làm DSL, bộ lọc query hay công thức phức tạp, dùng hẳn parser như lark, pyparsing, hoặc module ast có sẵn kèm visitor an toàn sẽ nhanh và sạch hơn nhiều.

Khi nào dùng Interpreter?

Hỏi: Khi nào tôi nên dùng Interpreter?

Đáp: Khi bạn có một bộ quy tắc nhỏ gọn hoặc biểu thức logic cố định (ví dụ filter tìm kiếm, công thức tính giá, máy tính mini) cần đánh giá lặp đi lặp lại trên nhiều bộ dữ liệu context khác nhau.

Đầu vào:

Các biểu thức kết hợp số, biến (x, y), phép cộng và phép trừ, đánh giá với context = {"x": 5, "y": 3}.

from abc import ABC, abstractmethod


class Expression(ABC):
    @abstractmethod
    def interpret(self, context: dict[str, int]) -> int:
        pass

Kết quả mong muốn:

Tính giá trị của (x + 10) - (y + 2) lần lượt với x = 5, y = 3 và x = 20, y = 4:

Result (x=5, y=3): 10
Result (x=20, y=4): 24

Triển khai Interpreter:

Cách viết không dùng Interpreter (cắt chuỗi thủ công):

Tách chuỗi bằng split() chỉ sống nổi với "5 + 10", gặp dấu ngoặc hoặc lồng nhiều tầng là gãy ngay.

def naive_eval(expr: str, context: dict[str, int]) -> int:
    tokens = expr.split()
    if len(tokens) != 3:
        raise ValueError(f"Unsupported nested expression: {expr}")

    def resolve(token: str) -> int:
        return context[token] if token in context else int(token)

    left, op, right = resolve(tokens[0]), tokens[1], resolve(tokens[2])
    if op == "+":
        return left + right
    if op == "-":
        return left - right
    raise ValueError(f"Unknown operator: {op}")


if __name__ == "__main__":
    print(naive_eval("x + 10", {"x": 5}))
    try:
        print(naive_eval("(x + 10) - (y + 2)", {"x": 5, "y": 3}))
    except ValueError as err:
        print(f"Error: {err}")

Cách viết dùng Interpreter:

from abc import ABC, abstractmethod


class Expression(ABC):
    @abstractmethod
    def interpret(self, context: dict[str, int]) -> int:
        pass


class Number(Expression):
    def __init__(self, value: int):
        self.value = value

    def interpret(self, context: dict[str, int]) -> int:
        return self.value


class Variable(Expression):
    def __init__(self, name: str):
        self.name = name

    def interpret(self, context: dict[str, int]) -> int:
        return context[self.name]


class Add(Expression):
    def __init__(self, left: Expression, right: Expression):
        self.left = left
        self.right = right

    def interpret(self, context: dict[str, int]) -> int:
        return self.left.interpret(context) + self.right.interpret(context)


class Subtract(Expression):
    def __init__(self, left: Expression, right: Expression):
        self.left = left
        self.right = right

    def interpret(self, context: dict[str, int]) -> int:
        return self.left.interpret(context) - self.right.interpret(context)


if __name__ == "__main__":
    # Build the expression tree for: (x + 10) - (y + 2)
    expression = Subtract(
        Add(Variable("x"), Number(10)),
        Add(Variable("y"), Number(2)),
    )

    print(f"Result (x=5, y=3): {expression.interpret({'x': 5, 'y': 3})}")
    print(f"Result (x=20, y=4): {expression.interpret({'x': 20, 'y': 4})}")

Một khi đã dựng xong cây biểu thức, bạn có thể tính lại cùng một công thức với hàng loạt context khác nhau mà không phải parse lại chuỗi. Trong dự án Python thực tế, hãy giữ tư duy cây biểu thức này nhưng kết hợp với lark hoặc module ast thay vì gõ tay cả rừng class.


Điều hướng series: Trước: BP10 - Mediator

Bài viết liên quan

yell@hoangyell:~ %

>hoangyell --status

Đang bận chở vợ con đi cafe & chơi với AI ☕🤖

Ủa ai réo Yell đấy? Cần tâm sự chuyện code hay collab thì ghé Instagram tui nè:

Ghé Instagram esc to close